/** * 通用防抖 composable * 替代各页面中手动 setTimeout/clearTimeout 的防抖模式 */ export function useDebounce() { let timer: ReturnType | null = null /** * 返回一个防抖化的函数 * @param fn 要防抖的函数 * @param delay 延迟毫秒数(默认 300ms) * @returns 防抖后的函数 */ function debounce void>(fn: T, delay = 300): (...args: Parameters) => void { return (...args: Parameters) => { if (timer !== null) clearTimeout(timer) timer = setTimeout(() => { timer = null fn(...args) }, delay) } } /** 清除等待中的定时器 */ function cancel() { if (timer !== null) { clearTimeout(timer) timer = null } } return { debounce, cancel } }