From 8dceff1c7c8097d8967e3b9a2c5736e8cf76589a Mon Sep 17 00:00:00 2001 From: hzj <1304805162@qq.com> Date: Tue, 9 Sep 2025 10:22:21 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=96=B0=E7=BB=84=E4=BB=B6):=20=E5=B0=81?= =?UTF-8?q?=E8=A3=85=E9=98=B2=E6=8A=96=E8=8A=82=E6=B5=81=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/useDebounce.js | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/utils/useDebounce.js diff --git a/src/utils/useDebounce.js b/src/utils/useDebounce.js new file mode 100644 index 0000000..2a702dc --- /dev/null +++ b/src/utils/useDebounce.js @@ -0,0 +1,43 @@ +import { getCurrentInstance, onUnmounted } from 'vue'; + +// 防抖 +export function useDebounce(fn, delay = 500) { + let timer = null; + let instance = getCurrentInstance(); // 获取当前组件实例 + + const debounced = (...args) => { + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + fn(...args); + }, delay); + }; + if (instance) { + // 自动注册卸载钩子(仅组件内生效) + onUnmounted(() => { + clearTimeout(timer); // 清理定时器 + timer = null; + }); + } else { + // 非组件环境返回手动清理方法 + debounced.cancel = () => { + clearTimeout(timer); + timer = null; + }; + } + + return debounced; +} + +// 节流 +export function useThrottle(fn, delay = 1000) { + let lastCall = 0; + + const throttled = (...args) => { + const now = Date.now(); + if (now - lastCall < delay) return; + lastCall = now; + fn(...args); + }; + + return throttled; +}