【问题标题】:Events not being received by parent component vue父组件vue没有收到事件
【发布时间】: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


【解决方案1】:

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>

【讨论】:

  • 这行得通,但如果你有多个事件,例如文本编辑器,代码看起来很丑。有没有封装/语法糖的方法?
  • @Sebi 您可以使用对象语法一次传递多个事件侦听器 - 该技术暗示了here,其工作原理类似于传递多个pros as an object
猜你喜欢
  • 2020-04-19
  • 2018-06-23
  • 2020-03-18
  • 2017-07-07
  • 2017-01-22
  • 1970-01-01
  • 2019-11-12
  • 2020-10-02
  • 2019-02-20
相关资源
最近更新 更多