前端 按钮 loading效果阻断不了快速点击,执行防抖操作进行阻断接口连续调用

需求描述:
页面中执行了按钮的连续点击操作,虽然前端在按钮中加了loading效果,但是发现,如果点击速度很快,那么loading效果来不及赋值并执行,此时就会出现连续的接口调用造成数据保存或流程数据出现错误或重复数据新增。
此时用防抖解决。

封装如下:

import { request as iceRequest } from 'ice';
import _ from 'lodash';

function debounceAsync(func, wait) {
  let timeout;

  return async function (...args) {
    clearTimeout(timeout);

    return new Promise((resolve) => {
      timeout = setTimeout(async () => {
        const result = await func(...args);
        resolve(result);
      }, wait);
    });
  };
}

const request = (url: string, option) => {
  if (option.method) {
    if (option.method.toUpperCase() === 'GET' && option.query) {
      option.params = option.query;
    }
    if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(option.method.toUpperCase()) && option.query) {
      option.data = option.query;
    }
  }
  return iceRequest({
    url,
    ...option,
  });
};


const debounceRequestFn = (url: string, option, delay = 500) => {
  if (option.method) {
    if (option.method.toUpperCase() === 'GET' && option.query) {
      option.params = option.query;
    }
    if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(option.method.toUpperCase()) && option.query) {
      option.data = option.query;
    }
  }
  return iceRequest({
    url,
    ...option,
  });
};

export default request;

const debounceRequest = debounceAsync(async function (url: string, option, delay = 500) {
  const response = await debounceRequestFn(url, option, delay);
  return response
}, 300)

export {
  debounceRequest
}

然后 在页面中引用方法即可

import request from '@/utils/request';
import debounceRequest from '@/utils/request';

你可能感兴趣的:(前端,防抖)