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.
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.
Import Vue from ‘Vue’; Export DefAULT New Vue ();
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
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 want to call BUS to listen to this event in the created () hook in the show assembly and receive parameters:
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.
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.