场景:

vue全局设置ajax的加载loading动效 以及不需要loading 页面的配置

请求方法:
import axios from 'axios'
import { baseURL } from '@/config'
import { getToken ,setToken} from '@/lib/util'
import { Indicator } from 'mint-ui'          //loading组件
class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  distroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      Indicator.close();   //请求完成 隐藏loading
    }
  }
  interceptors(instance, url) {
    instance.interceptors.request.use(config => {
      // 添加全局的loading..以及不需要loading 页面的配置
      let whiteList = ['/realTimeDetail','/order/list'];      //不添加loading 白名单
      if (!Object.keys(this.queue).length) {
        let valid = true;
        whiteList.forEach(reg=>{
          if(url.indexOf(reg) != -1){
            valid = false;
          }
        });
        if(valid){
          Indicator.open('loading...');
        }else{
          Indicator.close();
        }
      }
      this.queue[url] = true
      config.headers['Authorization'] = getToken('token')
      config.headers['version'] = getToken('version')
      config.headers['lang'] = localStorage.getItem('local')
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截器 两个参数 res(服务端返回的数据)
    instance.interceptors.response.use(res => {
      this.distroy(url)
      const { data } = res
      return data
    }, error => {
      this.distroy(url)
      return Promise.reject(error.response.data)
    })
  }
  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest

Logo

前往低代码交流专区

更多推荐