vue3自定义指令防抖和节流
时间: 2023-10-20 17:09:15 浏览: 114
在 Vue3 中,可以通过自定义指令来实现防抖和节流的效果。具体实现方式如下:
防抖指令:
```javascript
const debounce = (fn, delay) => {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};
const app = createApp({
// ...
});
app.directive('debounce', {
beforeMount(el, binding) {
const { value, arg = 'click' } = binding;
const fn = typeof value === 'function' ? value : () => {};
el.addEventListener(arg, debounce(fn, 500));
},
});
```
节流指令:
```javascript
const throttle = (fn, delay) => {
let timer = null;
return (...args) => {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
}
};
};
const app = createApp({
// ...
});
app.directive('throttle', {
beforeMount(el, binding) {
const { value, arg = 'click' } = binding;
const fn = typeof value === 'function' ? value : () => {};
el.addEventListener(arg, throttle(fn, 500));
},
});
```
阅读全文