Vue中使用防抖

防抖函数实现

方式一:多次点击只执行最后一次

1
2
3
4
5
6
7
8
9
10
/* 多次点击 只执行最后一次 */
const debounce = (function () {
let timer = null;
return function (func, delay = 1000) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(func, delay);
};
})();

方式二:先执行一次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* 先执行一次 */
const debounce2 = (function () {
let timer = null;
let flag = true;
return function (func, delay = 1000) {
if (flag) {
flag = false;
func.call();
return;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
flag = true;
func.call();
}, delay);
};
})();

export default {
debounce,
debounce2,
};

挂载到 Vue 原型

1
2
3
4
5
/* 挂载到原型 */
import debounce from "./debounce/debounce";
Vue.prototype.$utils = {
...debounce,
};

使用示例

1
2
3
4
/* 使用 */
this.$utils.debounce(() => {
// ...
}, 500);