优化一下这段代码watch: { scrollTop(newValue, oldValue) { setTimeout(() => { if (newValue == window.scrollY) { //延时执行后当newValue等于window.scrollY,代表滚动结束 this.oldScrollTop = newValue; //每次滚动结束后都要给oldScrollTop赋值 if (this.oldScrollTop > 100) { this.searchBgc = "#ccc"; // console.log(1111); } else { this.searchBgc = "transparent"; } } }, 20); //必须使用延时器,否则每次newValue和window.scrollY都相等,无法判断,20ms刚好大于watch的侦听周期,故延时20ms if (this.oldScrollTop == oldValue) { //每次滚动开始时oldScrollTop与oldValue相等 // console.log("滚动开始"); } },
时间: 2024-02-15 15:28:37 浏览: 20
可以优化代码如下:
watch: {
scrollTop: {
handler: function(newValue, oldValue) {
clearTimeout(this.timer); //清除之前的定时器
this.timer = setTimeout(() => {
if (newValue == window.scrollY) {
//滚动结束时执行
this.oldScrollTop = newValue;
if (this.oldScrollTop > 100) {
this.searchBgc = "#ccc";
} else {
this.searchBgc = "transparent";
}
} else {
//滚动中时执行
if (this.oldScrollTop == oldValue) {
//滚动开始时执行
// console.log("滚动开始");
}
}
}, 20);
},
immediate: true //立即执行handler函数
}
}
优化的主要点如下:
1. 使用 clearTimeout 清除之前的定时器,避免定时器叠加执行。
2. 将 handler 函数的内容拆分成滚动结束时执行和滚动中时执行两部分。
3. 使用立即执行模式(immediate: true)确保在组件创建时立即执行 handler 函数。