Sample Code for implementing sibling component communication in eventBus in vue2.0s, vue2.0seventbus
In vue1.0, the communication between components is mainly implemented through vm. $ dispatch propagation along the parent chain and vm. $ broadcast downstream broadcast. However, this method has been abolished in vue2.0.
After vuex is added, it provides clearer operations for communication between components. for medium and large projects, it is wise to plan vuex from the very beginning.
However, in some small projects, or just half of the projects I wrote, I found that vue2.0 could not use $. broadcast or $ dispatch. In this case, a convenient solution is required. Then, the role of eventBus is shown.
The main practical way is to introduce a new vue instance in the sibling components to communicate with each other, and then implement communication and parameter transmission by calling the event trigger and listener of the Instance separately.
Here is a simple example:
For example, we have three components: main. vue, click. vue, and show. vue. Click and show are the sibling components under the parent component main, and click is traversed in multiple list items in the parent component through v-. Here we need to implement it. After the click event is triggered in the click component, the show component will console the clicked dom element.
First, we add a click event to the click component.
<div class="click" @click.stop.prevent="doClick($event)"></div>
To implement communication to the show component in the doClick () method, we need to create a new js file to create our eventBus. we name it bus. js.
import Vue from 'vue'; export default new Vue();
In this way, a new vue instance is created. Next we will import it in the click component and show component.
import Bus from 'common/js/bus.js';
Next, we will trigger an event in the doClick method:
methods: { addCart(event) { Bus.$emit('getTarget', event.target); } }
Upload get follows the event.
Next, we need to call bus to listen to this event in the created () Hook of the show component and receive the parameters:
created() { Bus.$on('getTarget', target => { console.log(target); }); }
In this case, the event.tar get will be passed to show in each click event of a clickgroup, And the console will be displayed.
Therefore, eventBus is very convenient to use. However, it is recommended that you directly use vuex if it is a medium or large project with complicated communication.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.