一、安装axios
npm install axios --save
二、axios的封装
所封装的代码在 src/libraries/ 中,文件目录如下图:
具体代码如下:
src/libraries/utils/axios.js
import axios from ‘axios‘ import { Message, Loading } from ‘element-ui‘ //创建axios var instance = axios.create({ baseURL: ‘https://xxxxxxxxxxx‘, //接口域名 timeout: 10000, withCredentials: true, headers: { ‘accept‘: ‘application/json‘, ‘X-Requested-With‘: ‘XMLHttpRequest‘ } }) //使用instance发送请求 instance.interceptors.response.use((response)=>{ return response; }, (error) => { if (error && error.response) { const status = error.response.status switch (status) { case 401: Message.error(‘登录超时,请重新登录‘) window.location.href = error.response.data.error_uri + ‘/logout?callback=‘ + encodeURIComponent(window.location.href); break case 403: Message.warning(‘您没有操作该模块的权限,如要继续请联系管理员‘) break } } }) export default instance
src/libraries/utils/index.js
import axios from ‘./axios‘
export { axios }
src/libraries/plugins/axios.js
import { axios } from ‘../utils‘ export default Vue => { // mount the axios to Vue Object.defineProperties(Vue, { axios: { get: () => axios } }) // mount the axios to Vue component instance Object.defineProperties(Vue.prototype, { $axios: { get: () => axios } }) }
src/libraries/plugins/index.js
import axios from ‘./axios‘ export default { install (Vue) { axios(Vue) } }
最后在main.js中引入
import plugins from ‘./libraries/plugins‘
Vue.use(plugins);