演習 - 属性のバインディングを練習する

完了

宇宙クルーズの画像を顧客に表示したいとしましょう。 クルーズ アドベンチャーの種類ごとに画像が異なり、スタイルも異なる可能性があるため、画像のプロパティをアプリケーションのデータ オブジェクトに追加する必要があります。

プロパティをデータ オブジェクトに追加する

前の演習では、App オブジェクト内に data() メソッドを作成しました。 ここでは、画像のプロパティを追加します。

  1. index.js ファイルを開きます。

  2. // additional properties later のすぐ後ろに次のコードを追加します。

    productImage: 'assets/cruise.jpg',
    productImageDescription: 'An astronaut floats outside the window while you sit in comfort',
    productImageStyle: {
        'border-radius': '15px'
    }
    

これで、index.js ファイルに次のコードが含まれるようになりました。

const app = Vue.createApp({
    data() {
        return {
            productName: 'Book a Cruise to the Moon',
            productDescription: 'Cruise to the moon in our luxurious shuttle. Watch the astronauts working outside the International Space Station.',
            // additional properties later
            productImage: 'assets/cruise.jpg',
            productImageDescription: 'An astronaut floats outside the window while you sit in comfort',
            productImageStyle: {
                'border-radius': '15px'
            }
        }
    },
});

HTML を追加する

ここで、HTML を更新して画像を含めます。 属性バインディングを使用して属性とスタイルを設定します。

  1. index.html ファイルを開きます。

  2. <div>{{ productDescription }}</div> のすぐ後ろに次の HTML を追加します。

    <img :src="productImage" :alt="productImageDescription" :style="productImageStyle" />
    

    アプリの div 要素全体は、次のコードのようになります。

    <div id="app">
        <h2>{{ productName }}</h2>
        <div>{{ productDescription }}</div>
        <img :src="productImage" :alt="productImageDescription" :style="productImageStyle" />
    </div>
    

    すべての属性で、短縮表記 :attribute がどのように使用されているかに注意してください。 このように使用すると、長い v-bind:attribute 形式よりもコードが読みやすくなります。

結果をテストする

  1. すべてのファイルを保存します。

  2. ブラウザーで、ページに画像が表示されるようになりました。 表示されない場合は、ページを最新の情報に更新します。

    Screenshot of the updated page showing the image of the cruise.

  3. 画像を右クリックして、[検査] または [Inspect source](ソースの検査) を選択します。 ブラウザーおよび HTML の開発者ツールに注目してください。 HTML では、srcalt の両方が、Vue データの値に設定されていることに注意してください。

    <img src="assets/cruise.jpg" alt="An astronaut floats outside the window while you sit in comfort">
    

オプションを調べる

以上で、完全に機能的な Vue.js アプリケーションが作成されました。 一部の値やプロパティを変更すると、変更がページに反映されることを確認できます。

スタイルやクラスを CSS ファイルに自由に変更できます。 また、使用可能なバインディング オプションも調べてみてください。