问题发生场景是有一个组件被多个页面引用,该组件里有一个this.bus.on方法去监听页面事件的触发。在使用过程中发现每切换一次页面,然后触发事件,this.bus.on就会多响应一次,在查看vue-m-ts-bus插件的源码后发现每次声明this.bus.on就会加一个监听事件,我还发现this.bus.on方法调用后会返回一个id,也就是本次监听事件的id,后面去掉监听的时候会用到
$on (action, fn) {
if (!this[action]) {
this[action] = [fn]
} else {
**this[action].push(fn)**
}
this.$id = this.$id || 0
fn.$id = ++this.
**return fn.$id**
}
bus插件还定义了一个方法,off,这个方法就是用来取消监听事件的,这个事件有两个入参,一个是事件名称,一个是id,这个id就是on方法返回的id,只需要在使用的时候定义一个变量id去存储这个id就好了,
$off (action, id) {
if (!this[action]) {
return
}
if (id) {
this[action] = this[action].filter(fn => fn.$id !== id)
} else {
this[action] = null
}
}
存储监听ID
this.id = this.$bus.$on('retry', () => { // 监控重
//要做的处理
}
})
最后在组件销毁的生命周期里,调用off方法,并传入事件名称和id就好了
beforeDestroy() {
console.log('销毁');
this.$bus.$off('retry', this.id);
}