今天在项目的一个组件需要向兄弟组件传数据,所以想到了使用eventBus。
首先,我先建立了一个eventBus.js,代码如下:

import Vue from 'vue'
const eventBus = new Vue()
export default eventBus

然后在需要往外传值的组件中引用eventBus.js:

import eventBus from '@/assets/js/eventBus'

在方法中使用$emit往外传值:

eventBus.$emit('dataUpdate',data)

在需要接受值的兄弟组件中再次引用eventBus.js:

import eventBus from '@/assets/js/eventBus'

在created()周期函数里使用$on来接受其他组件传来的值:

created(){
  eventBus.$on('dataUpdate', item => {
    this.name = item
    console.log(this.name)
  })
}

然后我就遇到了一个奇怪的事情,console.log可以打印出this.name的值,但是页面上的name没有任何变化,还是data()函数里的初始值。
通过查询资料得知原来 vue路由切换时,会先加载新的组件,等新的组件渲染好但是还没有挂载前,销毁旧的组件,之后挂载新组件,如下图所示:

新组件beforeCreate
        ↓
新组件created
        ↓
新组件beforeMount
        ↓
旧组件beforeDestroy
        ↓
旧组件destroyed
        ↓
新组件mounted

注意,在$emit时,必须已经$on,否则将无法监听到事件。
所以正确的写法应该是在需要接收值的组件的created生命周期函数里写$on,在需要往外传值的组件的destroyed生命周期函数函数里写:

destroyed(){
  eventBus.$emit('dataUpdate',data)
}

这样写,在旧组件销毁的时候新的组件拿到旧组件传来的值,然后在挂载的时候更新页面里的数据。

Logo

前往低代码交流专区

更多推荐