首页 > 移动平台 > 详细

vue——axios安装及封装

时间:2021-08-06 17:32:40      阅读:46      评论:0      收藏:0      [点我收藏+]

一、安装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);

 

vue——axios安装及封装

原文:https://www.cnblogs.com/dreamstartplace/p/15102923.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!