Files
cz-web/src/directives/throttle.ts
wangzzpeng 7bc84bbe5e first
2026-09-24 10:10:43 +08:00

39 lines
1.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Directive } from 'vue'
interface ThrottleBinding {
handler: (...args: unknown[]) => void
interval?: number
}
type ThrottleValue = ThrottleBinding['handler'] | ThrottleBinding
const listenerMap = new WeakMap<Element, EventListener>()
function normalize(value: ThrottleValue): ThrottleBinding {
return typeof value === 'function' ? { handler: value } : value
}
/** v-throttle 节流点击:v-throttle="fn" 或 v-throttle="{ handler: fn, interval: 500 }" */
const throttle: Directive<Element, ThrottleValue> = {
mounted(el, binding) {
const { handler, interval = 500 } = normalize(binding.value)
let lastTime = 0
const listener: EventListener = () => {
const now = Date.now()
if (now - lastTime >= interval) {
lastTime = now
handler()
}
}
listenerMap.set(el, listener)
el.addEventListener('click', listener)
},
unmounted(el) {
const listener = listenerMap.get(el)
if (listener) el.removeEventListener('click', listener)
listenerMap.delete(el)
},
}
export default throttle