axios+element-ui封装全局loading

import axios from 'axios'
import Cookies from 'js-cookie'
import {
  Loading
} from 'element-ui';

const http = axios.create({
  baseURL: "",
  timeout: 1000 * 15
})


/**
 * 模拟一个出入栈
 */
let loadingInstance = null; // 记录页面中存在的loading
let loadingCount = 0; // 记录当前正在请求的数量

function showLoading(data) {
  if (loadingCount === 0) {
    loadingInstance = Loading.service({
      lock: true,
      text: data || '加载中……',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  }
  loadingCount++
};

function hideLoading() {
    if(loadingInstance && loadingCount != 0) {
        loadingCount--
        if (loadingCount === 0) {
            loadingInstance.close()
            loadingInstance = null
        }
    }
}


/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  if (!config.loadingHide) {//有的请求隐藏loading
      showLoading(config.loadingText)
  }
  config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  config.headers['token'] = Cookies.get('token') || ''

  return config
}, error => {
  return Promise.reject(error)
})



/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  if (!response.config.loadingHide) {//有的请求需要隐藏loading
      hideLoading()
  }
  
  return response
}, error => {
  if (!error.config.loadingHide) {//有的请求需要隐藏loading
      hideLoading()
  }

  return Promise.reject(error)
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值