❤️砥砺前行,不负余光,永远在路上❤️
目录
前言
节流: n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效
防抖: n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时
一、vue中防抖函数
使用场景:这里下拉框多选之后,三秒获取后边条件的列表数据(根据前边选择的内容获取新数据),直接使用
@change
的话选一个就会请求数据。
//防抖函数(select改变)
debounce(func, wait = 3000, immediate = false) {
// 清除定时器
if (this.timeout !== null) clearTimeout(this.timeout);
// 立即执行,此类情况一般用不到
if (immediate) {
var callNow = !this.timeout;
this.timeout = setTimeout(function () {
this.timeout = null;
}, wait);
if (callNow) typeof func === "function" && func();
} else {
// 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
this.timeout = setTimeout(function () {
typeof func === "function" && func();
}, wait);
}
},
注意:
data
中需要一个timeout
别忘了。
使用
changeSeList(val) {
let fn = async () => {
this.getSeList(); //这个方法是获取数据的
};
this.debounce(fn, 3000); //注意 这里直接传入this.getSeList() 不起作用
},