What is a proper way to communicate between sibling components in vuejs 2.0?

Technology CommunityCategory: Vue.jsWhat is a proper way to communicate between sibling components in vuejs 2.0?
VietMX Staff asked 3 years ago

With Vue 2.0, we using the eventHub mechanism.

Consider:

const eventHub = new Vue() // Single event hub

// Distribute to components using global mixin
Vue.mixin({
    data: function () {
        return {
            eventHub: eventHub
        }
    }
})
// your component you can emit events with
this.eventHub.$emit('update', data)
// And to listen you do
this.eventHub.$on('update', data => {
// do your thing
})

You can even make it shorter and use root Vue instance as global Event Hub:

// Component 1
this.$root.$emit('eventing', data);
// Component 2
mounted() {
    this.$root.$on('eventing', data => {
        console.log(data);
    });
}