0

基于:

https://forum.vuejs.org/t/passing-data-back-to-parent/1201 vue 按钮相关事件未触发

我有:

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中事件的范围是什么(wrt child-to-parent depth)

4

1 回答 1

2

this.$on正在尝试侦听组件发出的事件this,因此它正在侦听自身。

请注意,$on不应真正使用此 api ( )。它已从 Vue3 中删除,并导致设计不良的 Vue 应用程序。

要侦听您的子组件事件,请使用v-on或 shortand 语法@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>
于 2021-07-12T20:23:40.210 回答