Search code examples
javascriptvue.jsvuejs2vue-componentvue-events

Events not being received by parent component vue


Based on:

https://forum.vuejs.org/t/passing-data-back-to-parent/1201 vue button related event not fired

I have:

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

where the parent listens for events emitted by a child component:

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

where the child:

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

emits two events:

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

Why don't the events reach the parent? What's the scope of an event in vue (w.r.t. child-to-parent depth)


Solution

  • this.$on is trying to listener to the events emitted by the this component, so it's listening to itself.

    Note that this api ($on) shouldn't really be used. It has been removed from Vue3 and leads to a badly designed vue application.

    To listen to your child component events, use v-on, or the shortand syntax @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>