vue使用eventBus遇到数据不更新的问题及解决 |
vue使用eventBus遇到数据不更新问题今天在项目的一个组件需要向兄弟组件传数据,所以想到了使用eventBus 。 我先建立了一个eventBus.js代码如下: import Vue from 'vue' const eventBus = new Vue() export default eventBus 在需要往外传值的组件中引用eventBus.jsimport eventBus from '@/assets/js/eventBus' 在方法中使用$emit往外传值eventBus.$emit('dataUpdate',data) 在需要接受值的兄弟组件中再次引用eventBus.jsimport 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 注意在 所以正确的写法应该是在需要接收值的组件的 destroyed(){ eventBus.$emit('dataUpdate',data) } 这样写,在旧组件销毁的时候新的组件拿到旧组件传来的值,然后在挂载的时候更新页面里的数据 。 总结以上为个人经验,希望能给大家一个参考,也希望大家多多支持 。 |