watch 防抖设计

防抖的实现原理:

  • 用户输入数据时,watch 会被触发。

  • 防抖通过 设置一个定时器,如果在设定的时间间隔内,watch 被触发多次,那么只有最后一次触发会被执行。

  • 如果在设定的时间内没有触发,就会执行一次操作。

data() {
return {
searchText: '',
timer: null
}
},
watch: {
searchText(newVal) {
// 每次输入时,清除上次的定时器
clearTimeout(this.timer);

// 设置新的定时器
this.timer = setTimeout(() => {
this.search(newVal); // 延迟一段时间后执行搜索
}, 500); // 500ms 的防抖延迟
}
},
methods: {
search(query) {
console.log('搜索内容:', query);
// 执行搜索操作,发送请求等
}
}

 

可以用一个单独的防抖函数来封装

methods: {
debounce(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
},

search(query) {
console.log('搜索内容:', query);
// 执行搜索操作,发送请求等
}
},

created() {
// 在 created 中使用防抖函数
this.debouncedSearch = this.debounce(this.search, 500);
},
watch: {
searchText(newVal) {
this.debouncedSearch(newVal); // 调用防抖后的搜索函数
}
}

posted @ 2025-12-17 09:55  学无边涯  阅读(1)  评论(0)    收藏  举报