• 请求发起的时候开始loading,响应结束的时候关闭loading
/**
 * 全局请求方式
 */
import axios from 'axios'
import Vue from 'vue'

import router from '@/router/index'

import {Message,Loading} from 'element-ui' //项目已经全局引入element的话可以不单独引入

let loading = null //定义loading变量

//开始 加载loading
let startLoading=()=>{
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
//结束 取消loading加载
let endLoading=()=>{
  loading.close()
}

//showFullScreenLoading() 与 tryHideFullScreenLoading() 目的是合并同一页面多个请求触发loading

let needLoadingRequestCount = 0 //声明一个变量

let showFullScreenLoading=()=> {
    if (needLoadingRequestCount === 0) { //当等于0时证明第一次请求 这时开启loading
        startLoading()
    }
    needLoadingRequestCount++ //全局变量值++ 
}

let tryHideFullScreenLoading=()=> {
    if (needLoadingRequestCount <= 0) return //小于等于0 证明没有开启loading 此时return
    needLoadingRequestCount-- //正常响应后 全局变量 --
    if (needLoadingRequestCount === 0) {  //等于0 时证明全部加载完毕 此时结束loading 加载
        endLoading()
    }
}


const service = axios.create({
  baseURL: process.env.VUE_APP_BASEURL,
  timeout: 5000, // request timeout
  headers: {
    'Content-Type': 'application/json;'
    
  },
});



service.interceptors.request.use(
  config => {
    
    //开启loading加载
    showFullScreenLoading()
    return config
  },
  error => {
    return Promise.reject(error)
  }
);

service.interceptors.response.use(
  response => {

      //关闭loading加载
      tryHideFullScreenLoading()
      return Promise.reject(response.data)
    
  }, 
  error => {


    return Promise.reject(error)

  }
);



export default service

 

Logo

前往低代码交流专区

更多推荐