2

在项目目录中新建文件, 命名为axios.js, 复制以下代码, 其原理为在axios的请求和响应拦截中判断请求是否结束.


import vue from 'vue';
import axios from 'axios';
import { Loading } from 'element-ui'
// 定义请求次数(用于判断请求是否已经全部响应)
let requestCount = 0;
let loading;
// (客户端请求前)显示loading
function showLoading() {
  if (requestCount === 0) {
    loading = Loading.service({
      spinner: "mobile-loading",    //loading样式类名
      background: "rgba(0,0,0,0.8)"
    })
  }
  requestCount++
}
let timer;
// (服务器响应后)尝试隐藏loading
function tryHideLoading() {
  requestCount-- 
  //采用setTimeout是为了解决一个请求结束后紧接着有另一请求发起导致loading闪烁的问题
  timer = setTimeout(() => {    
    if (requestCount === 0) {
      loading.close()
      clearTimeout(timer)
    }
  })
}

let newAxios = axios.create({
  baseURL: "此处可设置项目的公共请求地址",
});

// 添加请求拦截器
axios.interceptors.request.use(function (config) {    
    showLoading()
    return config;
  }, function (error) {
    return Promise.reject(error);
  });
// 添加响应拦截器
axios.interceptors.response.use(function (response) {    
    tryHideLoading()
    return response;
  }, function (error) {
    return Promise.reject(error);
  });
  

const mixinObj = {
  data() {
    return {
      axios: newAxios,
    }
  }
};

// main.js文件中引入该文件之后, 可在*.vue文件中通过this.axiso.*直接发起请求
vue.mixin(mixinObj);

// 将处理后的axios示例暴露, 可以在*.vue文件中正常引入后使用
export default newAxios;

JustForSmiling
3 声望0 粉丝