简体   繁体   中英

Communication between sibling components in Vuejs

Communication between parent and child components are pretty straightforward using $broadcast and $dispatch

The issue I'm trying to wrap my head around is communication between sibling components. What I currently do is run a $dispatch on the child which is then caught by a event on the parent vm which in turn is $broadcast to the sibling component.

IE (non-functional, simplified example):

new Vue({
    components: { Brother, Sister },
    events: {
        'brother-to-sister-event': function(message) {
            this.$broadcast('message-to-sister', message);
        }
});

Brother
    this.$dispatch('brother-to-sister-event', message)

Sister
    events: {
        'message-to-sister': function(message) {
            alert('Message from Brother receiced!');
        }
    }

I just feel like I'm doing a lot of ping pong with how my data gets passed around between the sibling components. I couldn't really find a good example in the documentation for handling this. The above example is my best offert to solve it.

Does anyone have a good example of how to handle this in a more efficient way? What I'm aiming for is when I $broadcast or $dispatch from Brother, this will be picked up immediately by Sister. In doing so, I don't have to clutter up the root vm with intermediary events.

So the solution would be something like:

new Vue({
    components: { Brother, Sister }
});

Brother
    this.$dispatch('brother-to-sister-event', message)

Sister
    events: {
        'brother-to-sister-event': function(message) {
            alert('Message from Brother receiced!');
        }
    }

But I have not managed to get something like this to work.

Plain Vue.js communication of sibling components can only be done only through the parent as you are describing on your example.

A more sofisticated way to handle these cases for more complex apps is a central state manager.

Vue.js creator has published a redux like component that when used with vuejs updates their state though actions dispatched on stores. Then the 'reactiveness' of the vuejs framework picks up any changes made to the state of the component and re-renders them.

The documentation of the component is really nice
Vuex
Vuex Documentation
Vuex todo mvc example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM