在 Vue 3 中,子組件調用父組件的事件(或方法)的方式與 Vue 2 類似,但 Vue 3 引入了 Composition API,這可能會改變你組織代碼的方式。不過,基本的通信機制——通過自定義事件 ($emit
) 通知父組件——仍然保持不變。
以下是如何在 Vue 3 中使用 Options API 和 Composition API 的示例:
使用 Options API
父組件 (ParentComponent.vue)
<template>
<div>
<h2>父組件</h2>
<ChildComponent @child-event="handleChildEvent" />
</div>
</template> <script>
import ChildComponent from './ChildComponent.vue'; export default {
components: {
ChildComponent
},
methods: {
handleChildEvent(payload) {
console.log('子組件觸發的事件被父組件捕獲', payload);
}
}
};
</script>
子組件 (ChildComponent.vue)
<template>
<div>
<h3>子組件</h3>
<button @click="triggerParentEvent">觸發父組件事件</button>
</div>
</template> <script>
export default {
methods: {
triggerParentEvent() {
this.$emit('child-event', { message: '來自子組件的數據' });
}
}
};
</script>
使用 Composition API
父組件 (ParentComponent.vue)?(這里父組件使用 Options API 或 Composition API 都可以)
子組件 (ChildComponentWithComposition.vue)
<template>
<div>
<h3>使用 Composition API 的子組件</h3>
<button @click="triggerParentEvent">觸發父組件事件</button>
</div>
</template> <script>
import { defineComponent, ref } from 'vue'; export default defineComponent({
setup(props, { emit }) {
const triggerParentEvent = () => {
emit('child-event', { message: '來自使用 Composition API 的子組件的數據' });
}; return {
triggerParentEvent
};
}
});
</script>
在 Composition API 中,setup
?函數接收兩個參數:props
?和?context
。context
?是一個對象,它包含了?attrs
、slots
?和?emit
?等屬性。你可以通過?context.emit
?來觸發事件,但更常見的做法是將?emit
?直接從?setup
?函數的參數中解構出來,如上面的示例所示。
在這兩種情況下,子組件都通過?$emit
?方法觸發一個名為?child-event
?的事件,并將一些數據作為有效負載傳遞給父組件。父組件監聽這個事件,并在事件觸發時調用相應的方法。