From dabcfdd1f1a9346c61365b0ec583e58e696a91ab Mon Sep 17 00:00:00 2001 From: ileostar Date: Sun, 3 Mar 2024 18:48:58 +0800 Subject: [PATCH] chore: fix debounce & slideIn bugs --- src/directive/v-debounce/index.ts | 28 ++++++++++++++-------------- src/directive/v-slideIn/index.ts | 9 +++++---- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/directive/v-debounce/index.ts b/src/directive/v-debounce/index.ts index 68faa16..a2497df 100644 --- a/src/directive/v-debounce/index.ts +++ b/src/directive/v-debounce/index.ts @@ -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 void> = new WeakMap() @@ -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) @@ -58,5 +59,4 @@ const vDebounce: Directive = { addEventListener(el, binding) }, } - export default vDebounce diff --git a/src/directive/v-slideIn/index.ts b/src/directive/v-slideIn/index.ts index c29e002..6e8c2bb 100644 --- a/src/directive/v-slideIn/index.ts +++ b/src/directive/v-slideIn/index.ts @@ -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 } }) } @@ -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) },