vue3+ts 封装防抖函数加上加载动画超时关闭动画

为了防止按钮连续点击造成不必要的多次触发,给按钮触发加上防抖还是很有必要的。

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

 效果:

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值