Vue 3 事件處理:v-on 指令與參數傳遞
在前端開發中,與使用者的互動是建立動態網頁的核心。Vue 3 提供了直覺且強大的事件處理機制。本文將從最基礎的 v-on 語法開始,逐步深入到多參數傳遞、事件修飾符,以及 Vue 3 組合式 API(Composition API)中的實戰應用,幫助您徹底掌握 Vue 3 的事件處理技巧!
事件處理基礎:v-on 與 @
在 Vue 3 中,我們使用 v-on 指令來監聽 DOM 事件。因為這個指令極為常用,Vue 官方提供了縮寫語法 @。
html
<!-- 完整寫法 -->
<button v-on:click="clickHandler" type="button">按鈕</button>
<!-- 縮寫(推薦) -->
<button @click="clickHandler" type="button">按鈕</button>行內事件處理器
當事件觸發時,直接執行簡單的 JavaScript 運算式。這適用於非常簡單的邏輯,例如:計數器加減。
html
<!-- 行內表達式(適合簡單操作) -->
<button @click="count++" type="button">+1</button>
<button @click="isVisible = !isVisible" type="button">切換</button>方法事件處理器
當邏輯變得複雜時,將行內程式碼寫在 <template> 中會讓畫面變得難以維護。這時我們應該將邏輯抽離到 <script setup> 的函式中。
js
const { createApp, ref } = Vue;
const app = {
setup() {
const counter = ref(0);
// 無參數
function clickHandler() {
counter.value++;
}
// const clickHandler () => {
// counter.value++;
// }
// 接收事件物件
function inputHandler(e) {
console.log("輸入值:", e.target.value);
}
// const inputHandler = (e) => {
// console.log("輸入值:", e.target.value);
// };
return { counter, clickHandler, inputHandler };
},
};html
{{ counter }}
<button @click="clickHandler" type="button">increment</button>
<input @input="inputHandler" type="text" />進階參數傳遞:如何在事件中帶入自訂資料?
在實際開發中,我們經常需要在觸發事件時傳遞特定的參數,例如:商品的 ID。同時,我們可能也需要存取原生的 DOM 事件物件。
傳遞自訂參數
html
<button @click="deleteItem(1024)" type="button">刪除</button>同時傳遞自訂參數與原生事件物件
如果您既要傳入自訂參數,又需要原生 event 物件,可以使用 Vue 特定的行內變數 $event。
html
<button @click="handleClick(item, $event)" type="button">點擊</button>