问题描述
基于:
https://forum.vuejs.org/t/passing-data-back-to-parent/1201 vue button related event not fired
我有:
https://codesandbox.io/s/vigilant-mendeleev-hi4br?file=/src/components/GenericItem.vue
父组件监听子组件发出的事件:
mounted() {
this.$on("edit-category",(taskItemParam) => {
console.log("Received edit-category event with payload:",taskItemParam);
});
this.$on("delete-category",(taskItemParam) => {
console.log(
"Received delete-category event with payload:",taskItemParam
);
});
},
孩子在哪里:
https://codesandbox.io/s/vigilant-mendeleev-hi4br?file=/src/components/EditCategory.vue
发出两个事件:
<div class="modal-body" @click="emitEditCategory()">
<slot name="name"> Edit Name </slot>
</div>
<div class="modal-body" @click="emitDeleteCategory()">
<slot name="delete"> Delete Category </slot>
</div>
methods: {
...
emitEditCategory() {
this.$emit("edit-category",this.taskItemLocal);
console.log("Emitting edit-category");
},emitDeleteCategory() {
this.$emit("delete-category",this.taskItemLocal);
console.log("Emitting delete-category");
},},
为什么事件没有到达父级? vue 中事件的范围是什么(w.r.t. child-to-parent depth)
解决方法
this.$on
正在尝试侦听 this
组件发出的事件,因此它正在侦听自身。
请注意,不应真正使用此 api ($on
)。它已从 Vue3 中删除并导致 vue 应用程序设计不当。
要监听子组件事件,请使用 v-on
或简写语法 @my-event
:
<template>
<edit-category :taskItem="taskItemLocal" @edit-category="updateCategory" @delete-category="deleteCategory"/>
</template>
<script>
[...]
methods: {
updateCategory(task) {
// Do what you want
}
deleteCategory(task) {
// Do what you want
}
}
</script>