first
This commit is contained in:
38
src/directives/throttle.ts
Normal file
38
src/directives/throttle.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
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
|
||||
Reference in New Issue
Block a user