vue.js

Event handling with custom components in Vue.js

If you’ve been working with Vue.js lately and developing custom components to build your apps you might come across how to communicate from child component to parent. There are couple of scenarios here.

Immediate parent child components

If you want immediate parent-child components to communicate then a child event can fire an event and the parent can listen to it. To do this you can do something like this.

index.html

Vue.component('v-parent', {
 template: `
 `,
 
 methods: {
   handleEvent() {
     alert('parent caught the event');
   }
 }
});

Vue.component('v-child', {
 template: `
Fire Event
 `
});

new Vue({
 el: '#app'
});

app.js

Non-Parent-child components

If two different components want to communicate or if the component listening to the other component’s event is not a direct parent (like a grandparent or even above in the hierarchy) then Vue provides the bus concept. I have created a fiddle on JSFiddle that you can see running here.

Add a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.