parent 组件 vue 未接收到事件

Events not being received by parent component vue

基于:

https://forum.vuejs.org/t/passing-data-back-to-parent/1201

我有:

https://codesandbox.io/s/vigilant-mendeleev-hi4br?file=/src/components/GenericItem.vue

其中 parent 侦听 child 组件发出的事件:

  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
      );
    });
  },

其中 child:

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");
    },
  },

为什么事件没有到达 parent? vue中事件的范围是什么(w.r.t.child-to-parent深度)

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>