emit 說明
在 Vue.js 中,$emit 方法用於在子組件中向父組件發送自定義事件。這是一種子組件與父組件通信的常用方式。子組件使用 $emit 發出事件,父組件則使用 v-on 或 @ 指令來監聽這些事件並執行相應的處理邏輯。
使用 $emit 發送事件
當子組件需要告知父組件某些狀態或行為時,可以在子組件中使用 $emit 方法來發送事件。$emit 方法接受兩個參數:
- 事件名(必需):一個字符串,表示事件的名稱。
- 傳遞的參數(可選):可以是任意類型的數據,作為事件的附加信息。
範例
假設我們有一個 ChildComponent 組件,它需要在按鈕被點擊時通知父組件。這可以通過 $emit 方法來實現:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div> <button @click="notifyParent">Click me</button> </div> </template>
<script> export default { methods: { notifyParent() { this.$emit('child-clicked', 'Button was clicked!'); } } }; </script>
|
父組件監聽事件
父組件可以使用 v-on 或 @ 指令來監聽子組件發出的事件,並在事件被觸發時執行相應的處理函數。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <template> <div> <ChildComponent @child-clicked="handleChildClick" /> </div> </template>
<script> import ChildComponent from './ChildComponent.vue';
export default { components: { ChildComponent }, methods: { handleChildClick(message) { console.log(message); } } }; </script>
|
$emit 命名規範
使用小寫字母和短橫線(kebab-case):
自定義事件名稱應使用小寫字母和短橫線(kebab-case)。這與 HTML 屬性命名規範保持一致,並且在模板中使用時更具可讀性。
例如:user-clicked、item-selected、form-submitted。
$emit 驗證
1 2 3 4 5 6 7 8 9 10 11 12
| app.component('button-counter2', { emits: { add: (num) => { if (typeof num !== 'number') { console.warn('add 事件參數型別須為number') } } }, template: ` <button type="button" @click="$emit('add', '1')">Emit 驗證是否為數值</button> `, })
|
在內層元件定義 emits 來驗證型別