【发布时间】:2021-07-12 19:47:42
【问题描述】:
基于:
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)
【问题讨论】:
-
在mounted中调用它们有什么问题?他们不是。
-
Vue 中的事件范围只是子级到父级。它们不会冒泡或任何东西......从这个 POV 来看,“事件”这个名称是一个错误的选择,因为 Vue 中的事件与方法调用无关......
-
再次浏览文档尚不清楚当前示例与那里的示例有何不同; (除了在模板中注册了监听器)。
-
@Michal Levý 有没有类似广播方案的东西(不一定是事件总线(vuex))?
-
Vue 没有内置这样的东西。甚至“事件总线”模式也是stripped out in Vue 3
标签: javascript vue.js vuejs2 vue-component vue-events