vue——axios安装及封装

一、安装axios

  npm install axios --save

二、axios的封装

  所封装的代码在   src/libraries/   中,文件目录如下图:

  vue——axios安装及封装

 

  具体代码如下:

  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);

 

vue——axios安装及封装

上一篇:Oracle数据库命令行下数据的导入导出


下一篇:Fiddler 抓取Https时 显示 Tunnel to 443 的解决方案