vue使用eventBus遇到数据不更新问题
今天在项目的一个组件需要向兄弟组件传数据,所以想到了使用eventBus。
我先建立了一个eventBus.js
代码如下:
1 2 3 | import Vue from 'vue' const eventBus = new Vue() export default eventBus |
在需要往外传值的组件中引用eventBus.js
1 | import eventBus from '@/assets/js/eventBus' |
在方法中使用$emit往外传值
1 | eventBus.$emit( 'dataUpdate' ,data) |
在需要接受值的兄弟组件中再次引用eventBus.js
1 | import eventBus from '@/assets/js/eventBus' |
在created()周期函数里使用$on来接受其他组件传来的值
1 2 3 4 5 6 | created(){ eventBus.$on( 'dataUpdate' , item => { this .name = item console.log( this .name) }) } |
然后我就遇到了一个奇怪的事情
console.log可以打印出this.name的值,但是页面上的name没有任何变化,还是data()函数里的初始值。
通过查询资料得知原来 vue路由切换时,会先加载新的组件,等新的组件渲染好但是还没有挂载前,销毁旧的组件,之后挂载新组件
如下所示:
1 2 3 4 5 6 7 8 9 10 11 | 新组件beforeCreate ↓ 新组件created ↓ 新组件beforeMount ↓ 旧组件beforeDestroy ↓ 旧组件destroyed ↓ 新组件mounted |
注意
在$emit
时,必须已经$on
,否则将无法监听到事件。
所以正确的写法应该是在需要接收值的组件的created
生命周期函数里写$on
,在需要往外传值的组件的destroyed
生命周期函数函数里写:
1 2 3 | destroyed(){ eventBus.$emit( 'dataUpdate' ,data) } |
这样写,在旧组件销毁的时候新的组件拿到旧组件传来的值,然后在挂载的时候更新页面里的数据。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。