Vue+EventBus brother component pass value

In the project development, I encountered such a business:
suppose the parent component is A, the child components are B and C, and then the data structure of the C component is changed by the change of the B component, so I thought of using the event bus (EventBus) to carry out the sibling components communication between.
After using it, it is really easy to use, record and share a wave...

1. Under the utils folder folder, create a new bus.js (the name can be chosen at will)

import Vue from 'vue'
export default new Vue()

2. Import into brother components B and C

import EventBus from '@/utils/bus'

3. Communication between sibling components


Assuming that component B passes values ​​and component C receives values, component B passes values ​​through EventBus.$emit as common in other businesses :

const obj = {
    
    }
obj.name= res.name
obj.age= res.age
EventBus.$emit('modelObj', obj)

C components receive values ​​via EventBus.$on:

 EventBus.$on('modelObj', res => {
    
    
 // 此时就拿到了B组件传递的值
  console.log('res',res) 
})

Consider whether to remove the event bus according to the specific business scenario

EventBus.$off("eventName", callback); 只移除这个回调的监听器。
EventBus.$off('eventName'); 移除该事件所有的监听器。
EventBus.$off(); 移除所有的事件监听器,不需要添加任何参数。

At this point, you have mastered the communication method of EventBus.

Guess you like

Origin blog.csdn.net/pink_cz/article/details/126473014