Vue-监听事件、移除事件(节流处理)
业务:header(fixed定位)在顶部时是transparent的,当scroll触发,添加背景色;再次移动到顶端还是transparent的。depository:TYXX下面这一段代码,在组件卸载后destroyed会执行,但是scroll还是会继续触发。created() {window.addEventListener("scroll", this.throttle());},dest
·
业务:header(fixed定位)在顶部时是transparent的,当scroll触发,添加背景色;再次移动到顶端还是transparent的。
depository:TYXX
下面这一段代码,在组件卸载后destroyed会执行,但是scroll还是会继续触发。
created() {
window.addEventListener("scroll", this.throttle());
},
destroyed() {
window.removeEventListener("scroll", this.throttle());
}
// methods
throttle() {
let lastTime = new Date();
let timer = null;
return () => {
let startTime = new Date();
let remaining = 200 - (startTime - lastTime);
clearTimeout(timer);
if (startTime - lastTime > 200) {
lastTime = startTime;
this.scroll.call(this);
} else {
// 最后一次也执行
timer = setTimeout(() => {
this.scroll.call(this);
}, remaining);
}
};
}
问题的原因和“data为什么是函数”是一样的。节流函数throttle每次返回的函数是不一样的,所以,remove的函数和add的函数式不一样的。处理的方法就是对 节流 函数进行改造。(当然你也可以不节流就没有事了)
created() {
this.lastTime = new Date();
this.timer = null;
window.addEventListener("scroll", this.throttle);
},
destroyed() {
window.removeEventListener("scroll", this.throttle);
}
// methods
throttle() {
let startTime = new Date();
let remaining = 200 - (startTime - this.lastTime);
clearTimeout(this.timer);
if (startTime - this.lastTime > 200) {
this.lastTime = startTime;
this.scroll.call(this);
} else {
// 最后一次也执行
this.timer = setTimeout(() => {
this.scroll.call(this);
}, remaining);
}
}
效果:Perfect
更多推荐
已为社区贡献10条内容
所有评论(0)