安装
在vue项目里面
npm install axios
使用
在main.js里面,vue要先导入才行
import axios from 'axios'
Vue.prototype.$http = axios
在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 $http命令
methods: {
postData () {
this.$http({
method: 'post',
url: '/user',
data: {
name: 'xiaoming',
info: '12'
}
})
}
Get
直接拼接查询字符串
$http.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
/也可以通过 params 对象传递参数
$http.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Post
$http.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行多个请求
function getUserAccount() {
return $http.get('/user/12345');
}
function getUserPermissions() {
return $http.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then($http.spread(function (acct, perms) {
//两个请求现已完成
}));