天天看点

vue全局loading,axios拦截封装,api接口维护

vue全局loading

需求:

1,可配置每次发送请求时是否触发loading 。

2,请求结束后关闭loading。

3,连续请求时合并次数执行一次即可。

其实也是百度了好久经过测试真实好用的就是网友这个很棒

需要注意的点就是 要提前安装一下

npm i lodash -s

注意功能就是防抖的,不得不说很好用。

顺带也贴一下我的代码吧,基本也是复制的他的。复制过去只要安装好依赖基本都能使用。都是使用的

element-ui axios

在main.js 中引入该文档。

  • 包括了axios 的错误拦截,在这里可以把token写入header
  • 可以处理特殊的401 无权限问题 下面有调用案例。
import axios from "axios";
import { MessageBox, Message, Loading } from "element-ui";
import store from "@/store";
import _ from 'lodash';
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: "http://localhost:8090/public/", // process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
});
//loading对象
let loading;

//当前正在请求的数量
let needLoadingRequestCount = 0;

//显示loading
function showLoading(target) {
  // 后面这个判断很重要,因为关闭时加了抖动,此时loading对象可能还存在,
  // 但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
  console.log(needLoadingRequestCount,loading)
  if (needLoadingRequestCount === 0 && !loading) {
    loading = Loading.service({
      lock: true,
      text: "Loading...",
      background: "rgba(255, 255, 255, 0.5)",
      target: target || "body"
    });
  }
  needLoadingRequestCount++;
}

//隐藏loading
function hideLoading() {
  needLoadingRequestCount--;
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); //做个保护
  if (needLoadingRequestCount === 0) {
    //关闭loading
    toHideLoading();
  }
}

//防抖:将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时, loading闪烁的问题。
var toHideLoading = _.debounce(() => {
  loading.close();
  loading = null;
}, 300);

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    //if (store.getters.token) {
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // please modify it according to the actual situation
    // config.headers['X-Token'] = getToken()
    // }
    //判断当前请求是否设置了不显示Loading
    if(config.headers.showLoading !== false){
      showLoading(config.headers.loadingTarget);
    }
    config.headers.Authorization = `token 8889999`;
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    // if(config.headers.showLoading !== false){
    //   hideLoading();
    // }
    Message.error('请求超时!');
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    //判断当前请求是否设置了不显示Loading(不显示自然无需隐藏)
    if(response.config.headers.showLoading !== false){
      hideLoading();
    }
    if (res.code !== 0) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return ;
    }
    return res;
    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  error => {
    console.log("err" + error); // for debug
    //判断当前请求是否设置了不显示Loading(不显示自然无需隐藏)
    if(error.config.headers.showLoading !== false){
      hideLoading();
    }
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;

           

调用案例

我是单独封装了api ,方便维护。 调用时只需要给header写入true即可。

l里面导入的request 既是上面封装的axios 方法

import request from '@/utils/request'
export function login(data) {
  return request({
    url: 'user/login',
    method: 'post',
    headers:{'showLoading': true},
    data
  })
}
           

继续阅读