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.

Advertisements

Ask J

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s