axios拦截器中添加element-ui加载中组件loading的实现方法

element ui加载中组件

很多时候,页面在调取接口时,需要时间,此时为了页面有更好的交互性,通常都是有个加载中的显示,等页面渲染完成后,加载中消失。

element ui中loading组件的使用方法:

在哪个页面中需要使用,就在哪个页面中引用。
前提是已经引用了element ui

  1. 引入element ui中的loading组件
    import { Loading } from 'element-ui';
  2. 定义一个变量接收这个loading
    let loadingInstance1 = Loading.service({ fullscreen: true });
  3. 关闭加载中组件的方法
    loadingInstance.close();

下面展示一下在axios拦截器中Loading组件的使用

// response 拦截器\
//定义一个变量接收loading组件
let loadingInstance
service.interceptors.request.use(
//request 请求部分,在这个部分开启loading组件
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Content-Type'] = 'application/json'
    if (config.type && config.type === 'form') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      if (config.data) {
        config.data = qs.stringify(config.data)
      }
    }
    if (config.loading) {
      // eslint-disable-next-line no-const-assign
      //这行代码开始加载中组件,而且是全屏展示
      loadingInstance = Loading.service({ fullscreen: true })
    }

    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)
service.interceptors.response.use(
//接收到数据的处理部分,在这个部分关闭loading加载中组件
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      Notification.error({
        title: response.message
      })
      //如果有加载中组件,则关闭
      if (loadingInstance) {
        loadingInstance.close()
      }
      return Promise.reject('error')
    } else {
      if (loadingInstance) {
        loadingInstance.close()
      }
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.data.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        Notification.error({
          title: '网络请求超时',
          duration: 5000
        })
        return Promise.reject(error)
      }
    }
    if (code) {
      if (code === 401) {
        MessageBox.confirm(
          '登录状态已过期,您可以继续留在该页面,或者重新登录',
          '系统提示',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else if (code === 403) {
        router.push({ path: '/401' })
      } else {
        const errorMsg = error.response.data.message
        if (errorMsg !== undefined) {
          Notification.error({
            title: errorMsg,
            duration: 5000
          })
        }
      }
    } else {
      Notification.error({
        title: '接口请求失败',
        duration: 5000
      })
    }
    return Promise.reject(error)
  }

你可能感兴趣的:(element-ui的使用)