乐趣区

关于前端: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'
  })
}
退出移动版