简体   繁体   中英

Vuejs - exange informations between non parent-child components

I'm trying to exchange informations between two VueJs components.

Here is the situation :

Component A is the main component. B and C are into A, and D is into C.

I want to change a variable value of component D, from component B.

I've see here that if the components are using the same root component, we could done a broadcast from a first component to the root, then after get the broadcasted data from the root to a second component. But in my case, my component D is not directly in the root and deeper in the "components tree"... So, i tried and it would seem that this does not work.

What is the easiest way or more elegant way to do that ?

Thanks.

For something like this I'd use an Eventbus as described in the vue documentation; a blank Vue object for passing information agnostically.

window.EventBus = new Vue();

Then in your component that receives data, you'd create an event.

mounted: function () {
    EventBus.$on('name', function (data) {
        // Do something with the data
    });
}

Finally, in the component that sends data, you need to call that function.

methods: {
    someFunction: function () {
        EventBus.$emit('name', data);
    }
}

You can create a prototype link that provides access to the EventBus object for ease of use.

Vue.prototype.$eventBus = window.EventBus

Which you can access by using this.$eventBus.$on or this.$eventBus.$emit as seen in this jsFiddle .

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