防抖函数的运用

发过程中有要求做一个搜索框,在input输入框输入了文字之后就调一次接口,当用户输入过快就会疯狂调接口,很多接口返回数据后台并不是有用,因此使用了防抖函数。代码如下

函数debounce
export function debounce(fn, delay) {
let delays = delay || 500;
let timer;
return function () {
let th = this;
let args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
fn.apply(th, args);
}, delays);
};
}
使用
<input type="text" v-model="memberName" @input="onSearch">
 
import { debounce } from "@/common/js/debounce.js";
 
onSearch: debounce(function() {
//节流
let params = {
};
getProjectManagerList(params).then(res => {
let data = res.data.....
}
});
}, 1000),
原文地址:https://www.cnblogs.com/dmwcq/p/11180842.html