Vue 3 中通过 app.directive() 注册全局 v-debounce-throttle 指令,结合 utils 中纯函数实现防抖/节流,支持修饰符切换模式、动态事件与延迟,自动清理,TypeScript 友好,且用 import.meta.glob 批量注册。

Vue 3 项目中配置全局防抖与节流指令,核心是通过 app.directive() 注册自定义指令,并结合防抖/节流工具函数封装逻辑。关键不在于写多少代码,而在于结构清晰、可复用、自动清理、支持 TypeScript 和常见事件类型。
一、准备基础工具函数
在 src/utils/debounceThrottle.ts 中统一实现防抖与节流逻辑,避免重复:
- 防抖:触发后延迟执行,期间重复触发则重置计时器
- 节流:单位时间内最多执行一次,基于时间戳判断
- 导出两个纯函数,不依赖 Vue,便于单元测试或跨框架复用
export const debounce = <t extends any> any>(
fn: T,
delay: number
): ((...args: Parameters<t>) => void) => {
let timer: NodeJS.Timeout | null = null;
return (...args: Parameters<t>) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
};
<p>export const throttle = <t extends any> any>(
fn: T,
interval: number
): ((...args: Parameters<t>) => void) => {
let lastTime = 0;
return (...args: Parameters<t>) => {
const now = Date.now();
if (now - lastTime >= interval) {
fn(...args);
lastTime = now;
}
};
};</t></t></t></p></t></t></t>
二、注册全局指令(推荐单指令双模式)
不建议分别写 v-debounce 和 v-throttle 两个指令,而是用一个指令 v-debounce-throttle,通过修饰符切换行为,更简洁、易维护:
-
v-debounce-throttle:默认防抖 -
v-debounce-throttle.throttle:启用节流 - 支持传入延迟时间,如
v-debounce-throttle:500或v-debounce-throttle.throttle:300 - 自动监听
click、input等常用事件(可通过binding.arg指定,如v-debounce-throttle:input:300)
src/directives/debounceThrottle.ts 中定义:import type { App, Directive, DirectiveBinding } from 'vue';
import { debounce, throttle } from '@/utils/debounceThrottle';
<p>type Strategy = 'debounce' | 'throttle';</p><p>const directive: Directive = {
mounted(el, binding) {
const { value: handler, arg = 'click', modifiers } = binding;
const delay = Number(binding.instance?.$props?.delay || binding.arg?.split(':')?.[1]) || 300;
const strategy: Strategy = modifiers.throttle ? 'throttle' : 'debounce';</p><pre class="brush:php;toolbar:false;">if (typeof handler !== 'function') {
console.warn(`v-debounce-throttle expects a function, got ${typeof handler}`);
return;
}
const executor = strategy === 'debounce'
? debounce(handler, delay)
: throttle(handler, delay);
// 存储引用,用于更新和卸载
el._debounceThrottleHandler = executor;
el.addEventListener(arg, executor);
},
updated(el, binding) { el.removeEventListener(binding.arg || 'click', el._debounceThrottleHandler); // 重新挂载逻辑(同 mounted) const { value: handler, arg = 'click', modifiers } = binding; const delay = Number(binding.instance?.$props?.delay || binding.arg?.split(':')?.[1]) || 300; const strategy: Strategy = modifiers.throttle ? 'throttle' : 'debounce';
const executor = strategy === 'debounce' ? debounce(handler, delay) : throttle(handler, delay); el._debounceThrottleHandler = executor; el.addEventListener(arg, executor);
},
unmounted(el) { if (el._debounceThrottleHandler) { el.removeEventListener('click', el._debounceThrottleHandler); delete el._debounceThrottleHandler; } } };
export default directive;
三、批量自动注册(推荐)
在 main.ts 中使用 Vite 的 import.meta.glob 自动加载所有指令,无需手动一个个 app.directive():
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
<p>const app = createApp(App);</p><p>// 批量注册 directives 目录下所有指令
const directives = import.meta.glob('./directives/*.ts', { eager: true });</p><p>Object.keys(directives).forEach(key => {
const name = key.replace('./directives/', '').replace('.ts', '');
app.directive(name, (directives as any)[key].default);
});</p><p>app.mount('#app');</p>
- 目录结构:
src/directives/debounceThrottle.ts→ 指令名自动为debounceThrottle - 模板中直接写
v-debounce-throttle,无需额外导入 - 新增指令只需放文件,无需改入口,适合中大型项目
四、使用方式与注意事项
指令已就绪,使用非常直观:
- 按钮防抖提交:
- 搜索框节流输入:
- 自定义事件:
注意:避免在模板中直接调用带参函数如 v-debounce-throttle="onClick(123)",这会导致函数立即执行。应传入函数引用,参数通过闭包或事件对象传递。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










