The basic use
EventBus is suitable for transferring values between sibling components. Since this is a small project and you don’t need to use Vuex, consider using eventBus to transfer values between sibling components.
Steps:
-
Create a bus.js file, which you can place in the utility class directory, essentially creating a Vue instance to act as an eventBus.
import Vue from 'vue' export const bus = new Vue() Copy the code
-
Call the $emit method on the sending component to send data.
import {bus} from ".. /.. // import {bus}... // utils/bus.js" // import {bus}... Bus.$emit(parameter 1: 'define a method name ', parameter 2:' data to send ')Copy the code
-
The $on method is called on the receiving component to listen
import {bus} from ".. /.. /.. /utils/bus.js" ... Bus.$on('function(value){// value is the received value}')Copy the code
-
Finally, you can remove eventBus
EventBus.$off(' method name ', {})Copy the code
Scene, pit and cause
Due to the lazy loading used by the data receiving interface, when the data sending page calls the interface to get data, it will use $emit to send data, and then jump to the data receiving interface.
Therefore, $EMIT was executed before $ON, resulting in $ON not listening properly.
Solutions:
-
Don’t use lazy loading
-
When sending data, it is stored in the VUE instance. Jump to the interface for receiving data and then retrieve it
The concrete implementation is as follows:
Bus. Js file
Import Vue from 'Vue' export const Bus = new Vue({data () {return {// define data: {}}}, created () {/ / bind to monitor this. $on (' getInfo, value = > {this. Data = value})}}) ` ` `Copy the code
Sending data component
import {bus} from ".. /.. /utils/bus.js" ... Bus.$emit(parameter 1: 'define a method name ', parameter 2:' data to send ')Copy the code
Receiving data component
import {bus} from ".. /.. /utils/bus.js" computed: { records () { return bus.data } },Copy the code
Reference links:
Blog.csdn.net/qq_36490598…