Skip to content Skip to sidebar Skip to footer

How To Create A Hook With Events Between VUE 2.0 Components

I've created two dynamic components. Now, using events: $emit/$on what I need is to fire the 'logThat(someObj)' method of the component-two passing the arguments as you can see in

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 = new Vue();

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"