vue2.0之后,就不再对vue-resource更新,而是推荐使用axios
1. 安装 axios
$ npm install axios
或
$ bower install axios
2. 在要使用的文件中引入axios
import axios from 'axios'
3. 使用axios做请求
可以通过向 axios
传递相关配置来创建请求, 只有
url
是必需的。如果没有指定 method
,请求将默认使用 get
方法。
{
vue2.0之后,就不再对vue-resource更新,而是推荐使用axios
1. 安装 axios
$ npm install axios
或
$ bower install axios
2. 在要使用的文件中引入axios
import axios from 'axios'
3. 使用axios做请求
可以通过向 axios
传递相关配置来创建请求, 只有
url
是必需的。如果没有指定 method
,请求将默认使用 get
方法。
{
为方便,所有支持的请求方法都提供了别名:
4. 请求的响应结构
{ // `data` 由服务器提供的响应 data: {},
// status
来自服务器响应的 HTTP 状态码
status: 200,
// statusText
来自服务器响应的 HTTP 状态信息
statusText: ‘OK’,
// headers
服务器响应的头
headers: {},
// config
是为请求提供的配置信息
config: {}
}
使用 then
时,你将接收下面这样的响应:
axios.get('/user/12345') .then(function(response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); });
在使用 catch
时,响应可以通过 error
对象可被使用
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .catch(function (error) { console.log(error); });
5. 使用实例
el1: get请求
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
el2: post请求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
el3: 执行多个并发请求
function getUserAccount() { return axios.get('/user/12345'); }
function getUserPermissions() {
return axios.get(’/user/12345/permissions’);
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));