1.
npm install axios --save
2.
npm install @type/axios --save-dev(使用ts编写的需要此声明文件,升级的axios好像不需要了,已经自带)
3.
在src目录下添加axios.ts文件,内容:
import axios from 'axios' import {Notification} from 'element-ui' import store from './store/index' import buildconf from '../config/build.rootpath.js' axios.defaults.withCredentials = true; axios.defaults.baseURL = buildconf.serverUrl // axios.defaults.baseURL = 'http://gsblackwidow.chinacloudsites.cn/' axios.interceptors.request.use(function(config) { // document.getElementById('g-loader').style.display = 'flex' store.commit('requestModify', 1) return config; }, function(error){ return Promise.reject(error) }) axios.interceptors.response.use(function(response){ store.commit('requestModify', -1) // document.getElementById('g-loader').style.display = 'none' return response.data; }, function(error){ store.commit('requestModify', -1) // document.getElementById('g-loader').style.display = 'none' if(error.response.status === 401){ Notification({ title: '权限无效', message: '您的用户信息已经失效, 请重新登录', type: 'warning', offset: 48 }); window.location.href = '/#/login' }else{ Notification({ title: '请求错误', message: `${error.response.status} ${error.config.url}`, type: 'error', offset: 48, }) } return Promise.reject(error) }) export default axios
4.
main.ts中:
import axios from './axios'; Vue.prototype.$axios = axios
types文件夹中新建vue.d.ts文件,内容:
import {AxiosStatic, AxiosInstance } from 'axios' declare module 'vue/types/vue' { interface Vue { $axios: AxiosStatic; } }
这样就可以在各个模块中通过this.$axios来使用axios了
其中axios中:
1. build.rootpath.js内容:
var path = require('path') var rootpath = path.resolve(__dirname, '../dist') module.exports = rootpath
2. store是vuex的文件,所以要事先安装vuex