Skip to content

Commit

Permalink
chore: fix debounce & slideIn bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
ileostar committed Mar 3, 2024
1 parent a269f17 commit dabcfdd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 18 deletions.
28 changes: 14 additions & 14 deletions src/directive/v-debounce/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
/**
* @description: v-debounce指令
* @LastEditors: ileostar
* @LastEditTime: 2024/02/07 11:12:16
* @description: 防抖功能
*/
import type { Directive, DirectiveBinding } from 'vue'
import { isFunction } from '../../utils'
import { isFunction } from '../../utils/index'

const elMapToHandlers: WeakMap<Element, () => void> = new WeakMap()

Expand All @@ -23,12 +17,19 @@ function addEventListener(el: Element, binding: DirectiveBinding): void {
let timer: undefined | number

const handler = (): void => {
if (timer)
return
timer = window.setTimeout(() => {
value()
timer = undefined
}, delay)
if (timer === undefined) {
timer = window.setTimeout(() => {
value()
timer = undefined
}, delay)
}
else {
window.clearTimeout(timer)
timer = window.setTimeout(() => {
value()
timer = undefined
}, delay)
}
}

elMapToHandlers.set(el, handler)
Expand Down Expand Up @@ -58,5 +59,4 @@ const vDebounce: Directive = {
addEventListener(el, binding)
},
}

export default vDebounce
9 changes: 5 additions & 4 deletions src/directive/v-slideIn/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@ function isBelowViewport(el: HTMLElement) {
}

function handleScroll() {
const elements = document.querySelectorAll('[v-slide-in]')
const elements = document.querySelectorAll('[v-slideIn]')
elements.forEach((el: any) => {
if (isBelowViewport(el))
return

const animation = map.get(el)
if (animation) {
if (animation && !el.hasAttribute('v-slideIn-played')) {
animation.play()
el.removeAttribute('v-slide-in')
el.removeAttribute('v-slideIn')
el.setAttribute('v-slideIn-played', '') // Add a flag to mark the animation as played
}
})
}
Expand Down Expand Up @@ -53,7 +54,7 @@ const vSlideIn: Directive = {
)
animation.pause()
map.set(el, animation)
el.setAttribute('v-slide-in', '') // 添加标记,表示需要进行动画
el.setAttribute('v-slideIn', '') // 添加标记,表示需要进行动画

window.addEventListener('scroll', handleScroll)
},
Expand Down

0 comments on commit dabcfdd

Please sign in to comment.