vue bus使用的问题
vue bus.$on获取值并使用的问题
问题描述
使用bus.$on时,获取到回调函数的值后,第一时间无法使用,例如:
mounted() {
this.$bus.$on('bar', val => {
this.barData = val
})
console.log(this.barData) //undefined
this.$nextTick(() => {
console.log(this.barData) //undefined
})
setTimeout(() => {
console.log(this.barData) //能获取,但是建议少启用定时器
})
}
解决方法
- 使用定时器
- 在created生命周期中获取值,在mounted里使用
bus.$on 触发多次
解决方法
- 使用on接受前,使用off关闭
this.$bus.$off('bar')
this.$bus.$on('bar', val => {
this.barData = val
})