feat(新组件): 封装防抖节流功能组件
This commit is contained in:
parent
18bc43a4dc
commit
8dceff1c7c
43
src/utils/useDebounce.js
Normal file
43
src/utils/useDebounce.js
Normal file
@ -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;
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user