defineEmits - daniel-qa/Vue GitHub Wiki
在 Vue 3 的 script setup 中,defineEmits 用於定義子組件可以向父組件觸發的事件。這樣可以讓父組件監聽並響應子組件的事件。
在子組件 (Child.vue) 中
使用 defineEmits 定義要觸發的事件
使用 emit 來觸發事件,並可傳遞參數
在父組件 (Parent.vue) 中
監聽子組件觸發的事件 接收事件傳遞的數據,並執行相應邏輯
最簡單的範例
- 子組件 (Child.vue)
<template>
<button @click="sendMessage">點擊我</button>
</template>
<script setup>
import { defineEmits } from 'vue'
const emit = defineEmits(['sayHello'])
const sendMessage = () => {
emit('sayHello', 'Hello from child!')
}
</script>
- 父組件 (Parent.vue)
<template>
<Child @sayHello="handleSayHello" />
</template>
<script setup>
import Child from './Child.vue'
const handleSayHello = (message) => {
alert(message) // 彈出 "Hello from child!"
}
</script>