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 came across how to communicate from child component to parent. There are couple scenarios here.

Immediate parent child components

If you want immediate parent child components to communicate then child event can fire an event and 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 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.

Leave a Reply