vue项目全局设置ajax的加载loading动效

本文介绍如何在Vue中全局设置Ajax请求的loading效果及针对特定页面禁用loading的配置方法,通过使用mint-ui的Indicator组件实现加载动效,并设置白名单避免指定路由显示加载提示。
场景:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值