为了防止按钮连续点击造成不必要的多次触发,给按钮触发加上防抖还是很有必要的。
import { ElLoading } from 'element-plus';
import { ElMessage } from 'element-plus';
/**
* @description 防抖的函数的参数类型定义
*/
export interface DebThrEventParam {
/**
* @param 参数数据
*/
data: any;
/**
* @function 停止加载动画
*/
stopLoading: Function;
}
interface Config {
/**
* @param 防抖延迟时间
* @default 500
*/
delay?: number;
/**
* @param 是否启用加载
* @default false
*/
isLoading?: boolean;
/**
* @param 加载超时时间(默认5s)
* @default 5000
*/
timeuot?: number;
}
export function useMethod() {
/**
* @function 防抖
* @param fun 传过来处理的函数
* @param config 配置
* @returns
*/
const debounceEvent = (fun: Function, config?: Config) => {
let time: any = null;
let timeout: any = null;
return function (this: any, ...args: any) {
//默认配置
const defaut: Config = {
delay: 500,
timeuot: 5000,
isLoading: false,
...config,
};
//console.log(defaut, 'defaut');
//是否超时
let isTimeout = true;
if (time) clearTimeout(time);
time = setTimeout(() => {
time = null;
let loading: any = null;
if (defaut.isLoading) {
loading = ElLoading.service({
lock: true,
text: 'Loading',
background: 'rgba(0, 0, 0, 0.7)',
});
clearTimeout(timeout);
timeout = setTimeout(() => {
if (isTimeout) {
ElMessage({
message: '加载超时请重试',
type: 'error',
});
}
loading.close();
}, defaut.timeuot);
}
//关闭加载动画
const stopLoading = () => {
isTimeout = false;
if (loading != null) {
loading.close();
}
};
const data: DebThrEventParam = {
data: args,
stopLoading,
};
fun.call(this, data);
}, defaut.delay);
};
};
return {
debounceEvent,
};
}
使用: 给按钮绑定debounceEvent
效果: