congming_huose-apk/common/utils/debounce.js

94 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 防抖工具函数
* 用于防止用户快速多次点击导致重复执行
*/
// 存储每个按钮的点击状态
const clickStates = new Map();
/**
* 防抖点击装饰器
* @param {Function} func - 要防抖的函数
* @param {number} delay - 防抖延迟时间毫秒默认1000ms
* @param {string} key - 防抖标识符,用于区分不同的点击事件
* @returns {Function} 防抖后的函数
*/
export function debounceClick(func, delay = 1000, key = null) {
return function(...args) {
// 如果没有提供key使用函数的名称作为key
const debounceKey = key || func.name || 'default';
// 如果该key正在防抖中直接返回
if (clickStates.has(debounceKey)) {
console.log(`防抖拦截: ${debounceKey} 正在处理中...`);
return;
}
// 设置防抖状态
clickStates.set(debounceKey, true);
// 执行原函数
const result = func.apply(this, args);
// 延迟后清除防抖状态
setTimeout(() => {
clickStates.delete(debounceKey);
console.log(`防抖解除: ${debounceKey}`);
}, delay);
return result;
};
}
/**
* 创建防抖点击方法
* @param {Object} context - Vue组件实例上下文
* @param {string} methodName - 方法名
* @param {number} delay - 防抖延迟时间毫秒默认1000ms
*/
export function createDebounceMethod(context, methodName, delay = 1000) {
const originalMethod = context[methodName];
if (typeof originalMethod !== 'function') {
console.warn(`方法 ${methodName} 不存在`);
return;
}
context[methodName] = debounceClick(originalMethod.bind(context), delay, methodName);
}
/**
* 批量创建防抖方法
* @param {Object} context - Vue组件实例上下文
* @param {Array} methods - 方法名数组
* @param {number} delay - 防抖延迟时间毫秒默认1000ms
*/
export function createDebounceMethods(context, methods, delay = 1000) {
methods.forEach(methodName => {
createDebounceMethod(context, methodName, delay);
});
}
/**
* 清除所有防抖状态(用于页面销毁时清理)
*/
export function clearAllDebounceStates() {
clickStates.clear();
}
/**
* 检查某个key是否正在防抖中
* @param {string} key - 防抖标识符
* @returns {boolean} 是否正在防抖中
*/
export function isDebouncing(key) {
return clickStates.has(key);
}
/**
* 手动清除某个key的防抖状态
* @param {string} key - 防抖标识符
*/
export function clearDebounceState(key) {
clickStates.delete(key);
}