Categories
Vue Answers

How to emit event from grandchild to his grandparent component with Vue.js?

Spread the love

Sometimes, we want to emit event from grandchild to his grandparent component with Vue.js

In this article, we’ll look at how to emit event from grandchild to his grandparent component with Vue.js.

How to emit event from grandchild to his grandparent component with Vue.js?

To emit event from grandchild to his grandparent component with Vue.js, we call $emit in the grand child component.

Then in the parent component, we pass the events from the child to the grandparent with v-on="$listeners.

And then we listen to the event emitted from the grandchild component in the grandparent.

For instance, we write

Vue.component("grand-child", {
  //...
  methods: {
    emitToggleEvent() {
      this.$emit("toggle-value");
    },
  },
});

to call this.$emit in the grand-child component to emit the toggle-value event.

Then in the parent component of the grand-child, we write

Vue.component("child", {
  template: `<div class="child">
      <grand-child v-on="$listeners"></grand-child>
    </div>`,
});

to pass all events to the child‘s parent with v-on="$listeners".

Finally, in the parent component, which is the parent of the child component, we listen to the toggle-value event with

Vue.component("parent", {
  template: `div>
      <child @toggle-value="toggleValue"></child>
    </div>`,
  //...
});

Conclusion

To emit event from grandchild to his grandparent component with Vue.js, we call $emit in the grand child component.

Then in the parent component, we pass the events from the child to the grandparent with v-on="$listeners.

And then we listen to the event emitted from the grandchild component in the grandparent.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *