Communication between components

What is component communication? I believe all of you know that the most commonly used component communication is nothing more than child to parent, parent to child, penetration and store state management in the case of multiple levels. However, there is an unusual but very useful method ————>, which is eventBus.

Implement way

A new instance of VUE is introduced among the sibling components that are communicating with each other, and communication and parameter passing are implemented by invoking event triggers and listeners of this instance, respectively.

example

Here we take Vue to do a simple example, page A. Vue, B. Vue.

A.vue selects the dropdown method handleCommand

    <el-dropdown trigger='click' @command='handleCommand'>
    
Copy the code

We want to throw the default value of the selected dropdown in A.ue for the sibling component to see. We need to create a new JS file to create our eventBus, which we’ll call bus.js

import Vue from 'vue'
export default new Vue()
Copy the code

This creates a new vUE instance, which we then introduce in the A.vue component.

import Bus from './bus'
Copy the code

Next we fire an event in the handleCommand method of the A component

 handleCommand(command) {
    Bus.$emit('handleFunc', { command })
  }
Copy the code

Here we trigger handleFunc each time we select it, passing the event parameters along the event.

Next in the CREATED () life cycle of the B component

Bus.$on('handleFunc', 'handleFunc') {Bus.$on('handleFunc', 'handleFunc'); Command => {console.log(command) // to get the value we passed})}Copy the code

Don’t forget to turn off the listener when you’re done

 beforeDestroy() {
    Bus.$close('handleFunc')
 },

Copy the code

Let’s look at a real example

We need to throw the value of the selected node from the tree’s embedding function and pass it to the grandparent. Let’s look at the implementation

Selection method

EventBus communication

The grandparent component gets the selected value and the current node selected node information

Turn off eventBus listening when the page dies