2024-12-13 @input=updateNote 這是什麼意思??

2024-12-13 @input=updateNote 這是什麼意思??

@input="updateNote" 是 Vue 的事件綁定語法,表示當某個 DOM 元素觸發 input 事件時,執行名為 updateNote 的方法或函數。

語法拆解

  1. @ 是 Vue 的事件綁定簡寫

    • 在 Vue 中,@v-on 指令的縮寫。
    • 完整寫法是:v-on:input="updateNote"
    • v-on 用於監聽 DOM 元素的事件,例如 clickinputchangesubmit 等。
  2. input 是事件名稱

    • input 事件是在輸入框(如 <input><textarea>)的值改變時觸發的事件。
    • 每次用戶輸入新字元時,該事件都會觸發,更新相關的響應式數據。
  3. updateNote 是方法名

    • input 事件被觸發時,Vue 會執行 updateNote 方法。
    • 這個方法需要在 Vue 組件中定義。

範例:@input 用法

HTML:

1
2
3
4
5
<template>
<div>
<input type="text" @input="updateNote" placeholder="輸入筆記" />
</div>
</template>

JavaScript:

1
2
3
4
5
6
7
8
9
<script>
export default {
methods: {
updateNote(event) {
console.log("輸入的內容是:", event.target.value); // 獲取輸入框的值
},
},
};
</script>

執行流程:

  1. 當用戶在輸入框中輸入文字時,會觸發 input 事件。
  2. Vue 會執行 updateNote 方法。
  3. event.target.value 會獲取輸入框的最新內容。

v-model 的區別

  • @input 監聽事件,適用於執行自定義邏輯。
  • v-model 是雙向綁定,會自動同步數據與輸入框的值。

比較範例

使用 @input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
<input type="text" @input="updateNote" />
</template>

<script>
export default {
data() {
return {
note: "",
};
},
methods: {
updateNote(event) {
this.note = event.target.value; // 手動更新數據
},
},
};
</script>

使用 v-model

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<input type="text" v-model="note" />
</template>

<script>
export default {
data() {
return {
note: "", // 自動同步數據
};
},
};
</script>

@input 的適用場合

  • 當你需要在用戶輸入的過程中執行某些邏輯(如格式化數據、存入 LocalStorage)時,使用 @input
  • 如果只是簡單的數據雙向綁定,使用 v-model 更簡潔。