博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vue-cli的项目中关于axios的全局配置,结合element UI,配置全局loading,header中做token传输...
阅读量:4691 次
发布时间:2019-06-09

本文共 3262 字,大约阅读时间需要 10 分钟。

  在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

你可能感兴趣的文章
第四组-16通信2班-056 OSPF、OSPFv3协议
查看>>
新霸哥带你进入java的世界
查看>>
省选专练IOI2000邮局(S4共享单车)
查看>>
1.1 为什么要使用lambda 表达式
查看>>
第八周作业
查看>>
bzoj 3462: DZY Loves Math II
查看>>
Minimum Depth of Binary Tree
查看>>
【python】详解map函数的用法之函数并行作用解析
查看>>
单调队列与DP
查看>>
程序猿年终总结:我看了我的这7年
查看>>
handler的使用
查看>>
如何让wp7真机调试时候保持屏幕高亮不锁屏
查看>>
网络编程
查看>>
window下python安装pip
查看>>
【剑指offer】Q14:调整数组顺序使奇数位于偶数前面
查看>>
CSS3 Flexbox轻松实现元素的水平居中和垂直居中
查看>>
iOS开发UI篇—无限轮播(新闻数据展示)
查看>>
匿名内部类
查看>>
JPA entity versioning (@Version and Optimistic Locking)
查看>>
C# 通过 HTTPModule 防范 DOS
查看>>