记录一个VUE中防抖的小问题
记录一个VUE中防抖的小问题
export function debounce(fn, delay) {
let timer = null;
return function(...args) {
// 若定时器已存在则清除定时器
if (timer) {
clearTimeout(timer);
} // 新建一个定时器,在delay后触发方法
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
vue
<h-button @click="debounceClick">提交</h-button>
import { debounce } from "@/utils/index";
错误写法
methods: {
debounceClick() {
debounce(function(){
this.submitForm();
}, 1000)
}
}
问题出现原因:这里的debounceClick记得不要加()debounce返回的是function
methods: {
debounceClick: debounce(function(){
this.submitForm();
}, 1000)
}