vue brothers components pass the problems encountered when the value of the central event bus and use

Value pass between components may have various methods is used:
transmitting data between the parent-child assembly, subassembly to receive data transmitted by the parent component The props;
transfer of data between components brothers, using vuex,
but for simple communication requirements between components, vue official website provides a simpler method is called the central event bus;
the following outlines the steps the central event bus and the recent development in the use of a central data bus encountered.
First, create a central event bus, creating a eventBus.js in src / assets / under, reads as follows:

import Vue from 'Vue'
export default new Vue;

We have created a Vue instance, it is the communication bridge between components

Second, creating a component A, a component B, this event is introduced eventBus bus A, the component B ', respectively,

import bus from '../assets/eventBus';

Third, the information transfer from component A

bus.$emit("event",msg);//event是自定义事件名称;msg是需要传递的参数

$ Emit an instance method is equivalent to the trigger event on the bus, additional parameters are passed to the callback listener

Fourth, the acceptance information in the component B

mounted(){
	bus.$on("event",(msg)=>{...});//第二个参数是个回调函数,就是传过来的参数为msg,在将msg传给这个回调函数
}

1. monitor mounted in the event and pass arguments to pass over the callback function on the listener
2. must be written in mounted inside.

These are the basic steps of the central event bus.
But the situation I recently encountered in the development, because in the mounted monitor, can only initialize once, if you want to save the information passed in the past (state), (such as navigation information call the back end, when the click information, a component this information is displayed, the middle and jump to the other components, jump back, this component is to keep this information)
which need to be saved after the state passed by value between components that trigger bus. need to record the state $ on event this condition can be recorded on a url or cookie, and then take the time from which data can be.

Published an original article · won praise 0 · Views 24

Guess you like

Origin blog.csdn.net/cherryjia99/article/details/104341998