UNPKG

qvt-cli

Version:

提供多端响应式设计的模板框架

31 lines (29 loc) 1 kB
function debounce(func: (...args: any[]) => void, wait: number) { let timeout: ReturnType<typeof setTimeout> | null; return function (this: any, ...args: any[]) { if (timeout !== null) { clearTimeout(timeout); } timeout = setTimeout(() => func.apply(this, args), wait); }; } export const debounceDirective = { mounted(el: HTMLElement, binding: any) { if (typeof binding.value !== 'function') { console.warn( 'The value of the v-debounce directive should be a function', ); return; } const wait = binding.arg ? parseInt(binding.arg as string, 10) : 300; const debouncedFunction = debounce(binding.value, wait); el.addEventListener('click', debouncedFunction); (el as any)._debounce = debouncedFunction; // Save the function to remove it later }, unmounted(el: HTMLElement) { if ((el as any)._debounce) { el.removeEventListener('click', (el as any)._debounce); delete (el as any)._debounce; } }, };