vue-cli配置axios

1. javascript

npm install axios --savevue

2. java

npm install @type/axios --save-dev(使用ts編寫的須要此聲明文件,升級的axios好像不須要了,已經自帶)ios

3. vuex

在src目錄下添加axios.ts文件,內容:npm

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} \n ${error.config.url}`,
      type: 'error',
      offset: 48,
    })
  }
  return Promise.reject(error)
})

export default axios

4.element-ui

main.ts中:axios

import axios from './axios';
Vue.prototype.$axios = axios

  

types文件夾中新建vue.d.ts文件,內容:flex

import {AxiosStatic, AxiosInstance } from 'axios'
declare module 'vue/types/vue' {
  interface Vue {
    $axios: AxiosStatic;
  }
}

 

這樣就能夠在各個模塊中經過this.$axios來使用axios了ui

 

其中axios中:

1. build.rootpath.js內容:

var path = require('path')
var rootpath = path.resolve(__dirname, '../dist')
module.exports = rootpath

2. store是vuex的文件,因此要事先安裝vuex

相關文章
相關標籤/搜索