vue 中使用 eventBus

774 阅读1分钟

vue 中使用 eventBus

场景:需要兄弟组件传数据

  • 建立 eventBus
import Vue from 'vue'

export default new Vue()

  • 在需要往外传值和接受值的兄弟组件中使用 eventBus
import Bus from '@/utils/eventBus'
  • 往外传值的组件
eventBus.$emit('getParams',data)
  • 接收数据的组件处理
created(){
    eventBus.$on('getParams', item => {
        this.name = item
        console.log(this.name)
    })
}

出现异常:console.log 可以打印出 this.name 的值,但是页面中的 name 没有任何变化,还是 data 函数中的初始值; 原因:vue 路由切换时,会先加载新的组件,等新的组件渲染好但是还没有挂载前,销毁旧的组件,之后挂载新组件

新组件beforeCreate
        ↓
新组件created
        ↓
新组件beforeMount
        ↓
旧组件beforeDestroy
        ↓
旧组件destroyed
        ↓
新组件mounted
  • 正确写法 在需要接收值的组件的 created 生命周期函数里写$on,并且在每次使用完之后移除应用内所有对此事件的监听, 在需要往外传值的组件的 destroyed 生命周期函数函数里写:
    eventBus.$off('getParmas')
    
    destroyed(){
        eventBus.$emit('getParams',data)
    }