How To Create A Hook With Events Between Vue 2.0 Components
Solution 1:
Technically, you are supposed to use Non-parent-child communication as given in the docs.
But in your current example, it will not work. Reason: Your components 'one' and 'two' are getting created and destroyed as you move back and forth.
Here is your updated jsFiddle: https://jsfiddle.net/mani04/yuh71e1o/4/. Here are the changes:
Event bus:
var bus = newVue();
Sending event from component-one:
bus.$emit('selected', someObj);
Receiving event in component-two:
created: function() {
console.log("Created component-two, listening for 'selected' event");
bus.$on('selected', this.logThat);
}
If you open the dev console and observe the logs, you will notice that component-two gets created multiple times and the old ones keep listening as they are not fully destroyed.
To overcome this, you need to move away from dynamic components, and have both your component-one
and component-two
created at the same time on your root template. You may show / hide based on whichever view you desire, using v-show
(not v-if
which again destroys the component instance). Then you can use the event bus to communicate, as detailed in the Non-parent-child communication docs.
Post a Comment for "How To Create A Hook With Events Between Vue 2.0 Components"