Vue 本来有一个官方推荐的 ajax 插件 vue-resource,可是自从 Vue 更新到 2.0 以后,官方就再也不更新 vue-resource。vue
目前主流的 Vue 项目,都选择 axios 来完成 ajax 请求,而大型项目都会使用 Vuex 来管理数据,因此这篇博客将结合二者来发送请求ios
npm安装: git
npm install axios --save(一)、只使用axios配置github
注:安装其余插件的时候,能够直接在 main.js 中引入并使用 Vue.use()来注册,可是 axios并非vue插件,因此不能 使用Vue.use(),因此只能在每一个须要发送请求的组件中即时引入。ajax
为了解决这个问题,有两种开发思路,一是在引入 axios 以后,修改原型链,二是结合 Vuex,封装一个 aciton。npm
下面介绍的是经过修改原型来配置:axios
import axios from 'axios' Vue.prototype.$http = axios($http这个名字是随便起的,但要带上$,而且要与请求方式前面的名字保持一致!!!)api
main.js(全局配置)函数
import axios from 'axios' Vue.prototype.$http = axiosget请求:vue-resource
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))