演習 - 計算されるプロパティを追加する

完了

ここで、計算されるプロパティを作成して、選択されたキャビンに関する情報を表示します。 また、ページで選択を表示するために必要な HTML を追加します。

計算されるプロパティを追加する

計算されるプロパティを追加して、選択されたキャビンの文字列を表示します。

  1. Visual Studio Code で、index.js ファイルを開きます。

  2. TODO: Add computed values コメントの後の行に次の JavaScript コードを追加し、値を計算します。

    // TODO: Add computed values
    computed: {
        bookingCabinDisplay() {
            const cabin = this.product.cabins[this.booking.cabinIndex];
            return `${cabin.name}: $ ${cabin.price.toLocaleString('en-US')}`
        }
    },
    

this を使用して product.cabins にアクセスできることに注目してください。 booking.cabinIndex を使用して、ユーザーが選択したキャビンを検索します。 次に、ECMAScript テンプレートを使用して、表示文字列を作成します。

表示をページに追加する

ここで、表示をページに追加します。

  1. Visual Studio Code で index.html ファイルを開きます。

  2. TODO: Add success display コメントの後の行に次の HTML を追加し、予約を表示します。

    <!-- TODO: Add success display -->
    <div v-show="booking.completed">
        <h2 class="row">
            You are on your way!
        </h2>
        <div class="row">
            <div>Booking details:</div>
            <div>{{ bookingCabinDisplay }} </div>
            <div>Notes: {{ booking.notes }}</div>
        </div>
    </div>
    

booking.completedtrue に設定される場合、v-show を使用してコンテンツを表示することに注目してください。 これは、先ほどボタンに対して設定した動作です。 また、Vue 内の他の文字列値と同様に、bookingCabinDisplay を読み取って、ユーザーに表示できることにも注目してください。

ページをテストする

次に、操作中のページを確認します。

  1. [ファイル]>[すべて保存] を選択して、すべてのファイルを保存します。

  2. Ctrl + Shift + P キーを押してコマンド パレットを開きます。 Mac では、Cmd + Shift + P キーを押します。

  3. Live Server」と入力し、Live Server: Open with Live Server を選択して、Live Server を確実に実行します。

  4. ブラウザーを開き、http://localhost:5500 に移動します。 ページが表示されます。

  5. フォームに入力します。

    Screenshot of the completed form showing business class selected, and a request entered in the Notes field.

  6. ボタンを選択して、表示に注意します。

    Screenshot of the updated display showing the Booking details, indicating Business class, the price, and a note requesting a window seat.

以上で、計算されるプロパティが Vue アプリケーションに追加されました。