練習 - 新增事件處理常式
現在更新您的應用程式,為一個在表單上新增的按鈕建立事件處理常式。 此按鈕會切換 booking.completed
旗標以更新顯示項目。
新增函式
首先從將函式新增至 Vue 應用程式開始:
在 Visual Studio Code 中,開啟 index.js 檔案。
在
TODO: Add methods
註解之後的行上,新增下列程式碼以建立bookCabin
函式。 此函式為事件處理常式。// TODO: Add methods methods: { bookCabin() { this.booking.completed = true; } }
注意到
this
已與您目前的應用程式繫結。 它可讓您從資料存取booking
物件。
將按鈕新增至表單中
現在將按鈕新增至表單中:
在 Visual Studio Code 中,開啟 index.html 檔案。
在
TODO: Add button later
註解之後的行上,新增下列 HTML 來建立您的按鈕。<!--TODO: Add button later --> <button class="button" type="button" @click="bookCabin">Book now!</button>
請注意,
@click
屬性已與您稍早建立的bookCabin
函式繫結。
測試頁面
現在您可以開始測試剛才更新的頁面了!
- 請選取 [檔案]>[全部儲存] 以儲存全部檔案。
- 選取 Ctrl+Shift+P 以開啟命令選擇區。 在 Mac 上,請選取 Cmd+Shift+P。
- 輸入 Live Server 以確定 Live Server 正在執行,然後選取 [Live Server:以 Live Server 開啟檔案]。
- 開啟瀏覽器並移至至
http://localhost:5500
。 現在頁面上會顯示一個按鈕。 - 填寫表單並選取該按鈕。 請注意表單會從頁面中消失。
您現在已在 Vue 中設定了事件處理常式。