vue-cli的项目中关于axios的全局配置,结合element UI,配置全局loading,header中做token传输

  在src目录中建立plugins文件夹,在文件夹内建立axios.js文件

"use strict";

import Vue from 'vue';
import axios from "axios";
import {
  getCookie,
  delCookie,
  showFullScreenLoading,
  tryHideFullScreenLoading
} from '../utils/auth'
import {
  Message,
} from 'element-ui'

axios.defaults.headers.post['Content-Type'] = 'application/json';


let config = {
  baseURL: 'http://jiekou.com/', 
  timeout: 60 * 1000, // Timeout
  showLoading: true,//是否需要loading效果,如果不需要,则在请求时的第三个参数中传{showLoading:false}
  // withCredentials: true, // Check cross-site Access-Control
};

const token = getCookie('token');
const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    if (config.showLoading) {
      showFullScreenLoading()
    }
    config.headers.common['Authorization'] = 'Bearer ' + token;
    return config;
  },
  function (error) {
    // Do something with request error
    if (config.showLoading) {
      tryHideFullScreenLoading();
    }
    return Promise.reject(error);
  }
);
_axios.all = axios.all;
_axios.spread = axios.spread;
// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {

    if (config.showLoading) {
      tryHideFullScreenLoading();
    }
    if (response.data.Type == 401) {
      delCookie('token');
      Message.error('登录信息失效,稍后将自动为您转至登录页,请重新登录!');
      setTimeout(function () {
        location.href = '/login';
      }, 3000);
    }else if(response.data.Type==500 || response.data.Type==203){
      Message.error("警告:" + response.data.Content);
    }

    return response;
  },
  function (error) {
    if (config.showLoading) {
      tryHideFullScreenLoading();
    }
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;

  

  在axios文件中,我们引入了cookie操作和loading加载的方法。那么我们再来看看引入文件是什么。首先在src文件夹下创建utils文件夹,文件夹内创建auth.js。auth.js内是方法

import { Loading } from 'element-ui'
import _ from 'lodash'

export function getCookie(objName) {
  var arrStr = document.cookie.split("; ");
  for (var i = 0; i < arrStr.length; i++) {
    var temp = arrStr[i].split("=");
    if (temp[0] == objName) return unescape(temp[1]);
  }
}

export function delCookie(name){
  var date = new Date();
  date.setTime(date.getTime() - 10000);
  document.cookie = name + "=a; expires=" + date.toString();
}


/**
 * 全局loading的封装
 * **/

let loading;
let needLoadingRequestCount = 0;


function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}


const tryCloseLoading = () => {
  if (needLoadingRequestCount === 0) {
    loading.close()
  }
}


export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    _.debounce(tryCloseLoading, 300)();
  }
}


/**
 * 全局loading的封装
 * **/

  最后在main.js引入即可

import './plugins/axios'

返回目录

原文地址:https://www.cnblogs.com/gitByLegend/p/11047148.html