vue-cli 引入、配置axios的方法

发布时间:2020-08-24 16:56:20 作者:zeroyulong
来源:脚本之家 阅读:234

一、npm 安装axios,文件根目录下安装,指令如下

npm install axios --save-dev 

二、修改原型链,在main.js中引入axios

import axios from 'axios' 

接着将axios改写为Vue的原型属性,

Vue.prototype.$http=axios 

这样之后就可在每个组件的methods中调用$http命令完成数据请求

三、在组件中使用

methods: { 
   get(){ 
    this.$http({ 
     method:'get', 
     url:'/url', 
     data:{} 
    }).then(function(res){ 
     console.log(res) 
    }).catch(function(err){ 
     console.log(err) 
    }) 
     
    this.$http.get('/url').then(function(res){ 
     console.log(res) 
    }).catch(function(err){ 
     console.log(err) 
    }) 
   }    
}        

有关axios的配置请参考如下文档,点击打开链接

下面给大家介绍下vue-cli配置axios的方法

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

4.

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

总结

以上所述是小编给大家介绍的vue-cli 引入、配置axios的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

推荐阅读:
  1. express搭建纯后台,前台使用vue-cli脚手架
  2. 怎么搭建一个vue-cli的移动端H5开发模板

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue cli axios

上一篇:PHP使用convert_uuencode()函数对字符串进行编码的方法

下一篇:详解Docker 下开发 hyperf 完整使用示例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》