1)
vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现。
2)axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护。
axios在github上有详细的API使用说明 https://github.com/axios/axios#example
一、安装
- Using npm:
$ npm install axios
- Using bower:
$ bower install axios
- Using yarn:
$ yarn add axios
- Using jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- Using unpkg CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
二、简单使用案例
const axios = require('axios');
// 发起`get` 请求
axios.get('/user?ID=12345')
.then(function (response) {
// 请求成功后,这里处理返回数据
console.log(response);
})
.catch(function (error) {
//出现异常后,这里处理异常数据
console.log(error);
})
.then(function () {
// 这里 总是会进行,类似 `try`,`catch`,`finally`
});
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
三、同时发送多个ajax请求
ajax请求为异步请求,有的时候我们的操作需要建立在前面的请求都已经完成的情况下。
function getFirstName() {
axios.get('/user/12345/firstname');
....
}
function getLastName() {
axios.get('/user/12345/lastname');
...
}
axios.all([getFirstName(), getLastName()])
.then(axios.spread(function (acct, perms) {
// 现在所有的请求都已经完成
// 可以进行下一步操作了
}));
四、在axios请求中修改 / 获取vue实例的数据
我们直接在axios中是无法修改vue实例的数据的。
var vm = new Vue({
data: {
name: '',
},
methods: {
get_name() {
axios({
method: 'get',
url: '/user/name/',
}).then(function (response) {
this.name = response.data; //这里的 `this` 并不是 vm 实例对象
})
}
},
})
需要提前一步在get_name这个函数中获取this,因为get_name才是vue实例对象的方法。
new Vue({
data: {
name: '',
},
methods: {
get_name() {
var vm_obj = this // 获取 Vue 实例
axios({
method: 'get',
url: '/user/name/',
}).then(function (response) {
vm_obj.name = response.data; //这里的 `this` 并不是 vm 实例对象
})
}
},
})
五、axios发送请求的配置参数
我们可以使用以下方式,通过参数设置来完成发送请求,而不是像axios.get()这样高度耦合。
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
-
url:'/user/12345/name'请求的url地址 -
method:'get'请求方法,默认为get -
params:{ID: 12345}url参数,如果这里设置了,则url配置中可以不添加参数 -
data:{ firstName: 'Fred' }请求发送的数据,仅仅可以'PUT','POST', and'PATCH'请求中使用
支持的格式:
- string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
- Browser only: FormData, File, Blob
- Node only: Stream, Buffer
-
baseURL:'https://some-domain.com/api/'基础url配置。如果url是绝对url路径,则不会使用该配置 -
transformRequest:[],传入对请求信息进行处理的函数,可以传入多个
function (data, headers) {
// Do whatever you want to transform the data
return data;
}
-
transformResponse:[]传入对返回信息进行处理的函数,可以传入多个
function (data) {
// Do whatever you want to transform the data
return data;
}
headers:{'X-Requested-With': 'XMLHttpRequest'}设置请求头responseType:'json'返回的结果格式,默认为jsonresponseEncoding:'utf8'response编码,默认为utf8