eventBus in vue

In vue2, the parent and child components pass data, the parent component can directly pass data into the child component, and the child component passes its own data back by calling the method passed in by the parent component.

How to pass between sibling components, or between child components of sibling components?

Of course vuex is a solution, so what if you just use vue? Does it pass layer by layer?

Here is a brief description of the eventBus in vue2 .

A complete eventBus is mainly divided into three parts: eventBus component, register event ($on), send event ($emit)

 

eventBus component

import View from 'View';
export default new Vue;

Create an empty vue component to pass data

 

Registration issue

import EventBus from './eventBus';
EventBus.$on('eventname',(value) => { //value do someth });

 

send event

import EventBus from './eventBus';
EventBus.$emit('eventname', value);

 

It can be clearly seen from the code that we only need to introduce the eventBus component where we use it, and then register the $on event.

After the sending event $emit is triggered, EventBus will find the registered $on event of the same name by itself, and the next function is triggered like a jquery click event~

PS:

EventBus can be nested~

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324457282&siteId=291194637