在vue中,写在methods里面的方法,在页面切换时一般就自动销毁了,但是写在window上的事件,需要我们手动解绑,也是为了提高代码执行效率,案例如下:
1、 当我在新闻资讯页面执行滚动事件时,不断从控制台打印出1

2、切换到其他页面也会执行滚动事件

- 代码如下
// 滚动侧边栏浮动
sideFloat() {
// tslint:disable-next-line:no-console
console.log(1);
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
scrollTop > 410 ? this.isFloat = true : this.isFloat = false;
}
mounted() {
window.addEventListener("scroll", this.sideFloat);
}
解决方案,使用生命周期函数beforeDestroy,在页面离开时执行
// 对滚动事件绑定及解绑
beforeDestroy() {
window.removeEventListener("scroll", this.sideFloat);
}
这样就解决了对全局事件的解绑 +_+
网友评论