vue---axios

Vue 原本有一个官方推荐的 ajax 插件 vue-resource,但是自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource。

目前主流的 Vue 项目,都选择 axios 来完成 ajax 请求,而大型项目都会使用 Vuex 来管理数据,所以这篇博客将结合两者来发送请求

npm安装: 

npm install axios --save

(一)、只使用axios配置

注:安装其他插件的时候,可以直接在 main.js 中引入并使用 Vue.use()来注册,但是 axios并不是vue插件,所以不能 使用Vue.use(),所以只能在每个需要发送请求的组件中即时引入。

为了解决这个问题,有两种开发思路,一是在引入 axios 之后,修改原型链,二是结合 Vuex,封装一个 aciton。

下面介绍的是通过修改原型来配置:

import axios from 'axios' 
Vue.prototype.$http = axios

($http这个名字是随便起的,但要带上$,并且要与请求方式前面的名字保持一致!!!)

main.js(全局配置)

import axios from 'axios' 
Vue.prototype.$http = axios

get请求:

this.$http.get('/user?ID=12345')// 向具有指定ID的用户发出请求 
.then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });

或

this.$http.get('/user', {//也可以通过 params 对象传递参数 params: { ID: 12345 } }) 
.then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });

(二)、使用axios和vue-axios结合配置(不需要原型配置)

import Vue from 'vue'

import axios from 'axios'

import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

get请求:

this.axios.get('/user?ID=12345') 
.then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });

或

this.axios.get('/user', { params: { ID: 12345 } }) 
.then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });


 

 

附录:配置 axios 

上面封装的方法中,使用了 axios 的三个配置项,实际上只有 url 是必须的,完整的 api 可以参考使用说明

为了方便,axios 还为每种方法起了别名,比如上面的 saveForm 方法等价于:

axios.post('/user', context.state.test02)

完整的请求还应当包括 .then 和 .catch

.then(function(res){ console.log(res) }) 
.catch(function(err){ console.log(err) })
 

当请求成功时,会执行 .then,否则执行 .catch

这两个回调函数都有各自独立的作用域,如果直接在里面访问 this,无法访问到 Vue 实例

这时只要添加一个 .bind(this) 就能解决这个问题

.then(function(res){ console.log(this.data) }.bind(this))

 

 

转载于:https://my.oschina.net/u/3946362/blog/2209556

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值