Vue2.0s Eventbus implementing the sample code for brother component communication

In

Vue1.0, communication between components is mainly transmitted upwards through VM. $ Dispatch along the parent chain and uses VM. $ Broadcast to broadcast down. However, in Vue2.0, this usage has been abolished.

After VUEX is added, communication between components has a clearer operation. For medium largest projects, the use of Vuex’s usage plan is wise.


However, in some small items, or like this to find that Vue2.0 can’t use $ .Broadcast and $ Dispatch, you need a relatively convenient solution. . Then, Eventbus’ role is reflected.


It is mainly that the reality is to introduce a new Vue instance in the brothers component to communicate with each other, and then communicate and parameter delivery by calling the event triggered and listening to this instance.

Here is a simple example:

For example, we have three components here, main.vue, click.Vue, show.Vue. Click and Show are the brothers components under the parent component main, and the Click is traversed in a plurality of list items through V-FOR in the parent component. Here is to be implemented, after the Click component triggers the incident, which DOM element console will be clicked by the Show component.

First, we add a click event to the Click component



  
I want to communicate with the SHOW component in the doclick component, we need to create a JS file to create our Eventbus, we name it bus.js
Import Vue from ‘Vue’; Export DefAULT ​​New Vue ();

So we created a new Vue instance. Next we are imported in the Click component and the Show component.
 Import Bus from 'Common / JS / Bus.js';   
Next, we are in the Doculick method In the middle, to trigger an event:

Methods: {addcart (Event) {Bus. $ EMIT (‘getTarget’, event.target);}}
  Here we click on the Click component, which will trigger this event called 'getTarget' in BUS, and pass the event.target of the event to pass the event. 
Next, we want to call BUS to listen to this event in the created () hook in the show assembly and receive parameters:

Created {Bus. $ ON (‘gettarget’, target => {console.log (target);});}
   
In this Click Component In the event, the event.target will be passed to Show, and console comes out.


So the use of EventBus is still very convenient, but if it is a large project, communication is more complicated, or it is recommended that you use Vuex directly.

The above is the full content of this article, I hope to help everyone.Help, I also hope that everyone will support TUMI clouds.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment