Vue 中 Event Bus 事件总线

Event Bus 是 vue 中组件间数据传递的一种方式,通过一个 Vue 实例进行事件的派发和监听。值得注意的是,这种方式是非响应式的

1、初始化一个 EventBus,并向外共享

// 方式一: 直接新建一个 eventBus.js 文件,写入以下内容
import Vue from 'vue'
export const eventBus = new Vue()

// 方式二: 在入口文件 main.js 文件上直接初始化,并挂在到 Vue 原型上
import Vue from 'vue'
Vue.prototype.$eventBus = new Vue()

2、传递数据

// test1.vue 文件
import eventBus from './eventBus.js'
let userInfo = {
    
    name: 'bobo'}
eventBus.$emit('updateInfo', userInfo)

3、接收数据

// test2.vue 文件
import eventBus from './eventBus.js'
eventBus.$on('updateInfo', userInfo => {
    
    
    console.log(userInfo)
})

4、eventBus 移除事件

// test2.vue 文件
import eventBus from './eventBus.js'
export default{
    
    
    beforeDestory(){
    
    
        eventBus.$off('updateInfo')
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37600506/article/details/129671760