Element UI- Axios实现全局的loading自动显示

1、在request.js

import axios from 'axios';
import { Message,Loading } from 'element-ui';
import _ from 'lodash';

//loading对象
let loading;
  
//当前正在请求的数量
let needLoadingRequestCount = 0;

//显示loading
function showLoading(target) {
  // 判断是因为关闭时加了抖动,此时loading对象可能还存在,但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
  if (needLoadingRequestCount === 0 && !loading) {
    loading = Loading.service({
      lock: true,
      text: "Loading...",
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  }
  needLoadingRequestCount++;
}

//隐藏loading
function hideLoading() {
  needLoadingRequestCount--;
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // 取needLoadingRequestCount和0之间的最大值
  if (needLoadingRequestCount === 0) {
    //关闭loading
    toHideLoading();
  }
}
  
//防抖:将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时, loading闪烁的问题。
let toHideLoading = _.debounce(()=>{
      loading.close();
      loading = null;
    }, 300);

export default (
  appName ,
  type,
  {
    needSuccessTip = false,
    needErrorTip = true,
    loading = false,
    loadingText
  } = {}
) => {
  // 创建axios实例
  let baseURL = appName ? `${window.urlConfig[appName]}` : ''
  const service = axios.create({
    withCredentials: true,
    baseURL: process.env.BASE_URL, // api的base_url
    timeout: `${window.urlConfig.apiTimeout}`,
    headers: {
      token: localStorage.getItem('token'),
      'Content-Type': `application/${
        type === 'form' ? 'x-www-form-urlencoded' : 'json'
      };charset=UTF-8`
    }
  })
  //添加请求拦截器
  service.interceptors.request.use(res=> {
    if(loading){
      showLoading();
    }
    return res;
  }, 
  (err) => {
    if(loading){
      hideLoading();
    }
    Message.error('请求超时!');
    Promise.reject(error)
  });
  //响应拦截器
  service.interceptors.response.use(
      (res) => {
        if(loading){
          hideLoading();
        }
        return res;
      },
      error => {
        if(loading){
          hideLoading();
        }
        Message({
          message: error.message,
          type: 'error'
        })
        return Promise.reject(error);
      }
  )
  return service
}

2、在api

import request from '@/request'
export function getExportApi (params) {
  return request(
    '',
    '',
    {
      loading: true
    }
  )({
    url: 'xxx,
    method: 'get',
    params,
    responseType: 'blob'
  })
}

你可能感兴趣的:(前端axios)