1.安裝
npm install axios
2.使用
執行 GET 請求
// 爲給定 ID 的 user 創建請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可選地,上面的請求可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執行 POST 請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執行多個併發請求
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) {
// 兩個請求現在都執行完成
}));
3.axios API
transformResponse
在傳遞給 then/catch 前,允許修改響應數據。
<div id="app">
<button @click="handler">按鈕</button>
<h1>這是請求回來的數據{{msg}}</h1>
</div>
<script>
new Vue({
el : "#app",
data(){
return {
msg : ""
}
},
methods : {
handler(){
axios.get("http://xxx.com/1/report/index",{
transformResponse: [function (data) {
// 對 data 進行任意轉換處理
data = JSON.parse(data);
console.log(data[0].title);
data[0].title = 111
return data;
}]
})
.then((res) => {
console.log(res.data[0].title);
this.msg = res.data[0].title
}).catch((err) => {
});
}
}
})
</script>