优化一下这段代码 methods: { handleScroll() { window.addEventListener("scroll", () => { this.scrollTop = window.scrollY; }); }, returnFn() { // this.$router.go(-1); console.log(111); }, }, mounted() { this.handleScroll(); }, beforeDestroy() { window.removeEventListener("scroll"); //离开当前组件别忘记移除事件监听哦 }, async created() { try { // 轮播图 let { data } = await getSwiperApi(); this.swiperList = data.data.list; let res = await getGoodsListApi(); this.goodsList = res.data.data.list; // console.log(this.swiperList); // 活动 let active = await getActiveApi(); this.activeList = active.data.data.list; // console.log(this.activeList); } catch (err) { console.log(err); } }, 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函数 }, },
时间: 2024-02-15 07:28:37 浏览: 155
可以优化代码如下:
methods: {
handleScroll() {
this.handleScrollFn = () => {
this.scrollTop = window.scrollY;
}
window.addEventListener("scroll", this.handleScrollFn);
},
returnFn() {
// this.$router.go(-1);
console.log(111);
},
},
mounted() {
this.handleScroll();
},
beforeDestroy() {
window.removeEventListener("scroll", this.handleScrollFn); //移除事件监听
},
async created() {
try {
// 轮播图
let { data } = await getSwiperApi();
this.swiperList = data.data.list;
let res = await getGoodsListApi();
this.goodsList = res.data.data.list;
// console.log(this.swiperList);
// 活动
let active = await getActiveApi();
this.activeList = active.data.data.list;
// console.log(this.activeList);
} catch (err) {
console.log(err);
}
},
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,
},
},
优化的主要点如下:
1. 将事件监听函数 handleScroll 改为箭头函数,以便在 beforeDestroy 钩子中移除事件监听时可以正确地移除。
2. 在添加事件监听时,将 handleScroll 函数传递给 addEventListener,以便在 beforeDestroy 钩子中可以正确地移除事件监听。
3. 在 watch 中的 handler 函数中,同样将事件监听函数存储在变量中,以便在组件销毁时可以正确地移除事件监听。
4. 将 try/catch 包裹在 async/await 中,以便正确地捕获错误。
阅读全文