vue-cli的項目中關於axios的全局配置,結合element UI,配置全局loading,header中作token傳輸

  在src目錄中創建plugins文件夾,在文件夾內創建axios.js文件javascript

"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內是方法html

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引入便可vue

import './plugins/axios'

 


返回目錄

相關文章
相關標籤/搜索