Axios 是一個基於 Promise 的 HTTP 庫,可在瀏覽器和 node.js 中使用,本章節我們使用Axios 進行Ajax請求。
一、GET請求
參考下圖,在static中建一個demo.json文件:
demo.json:
{
"name":"AjazDemo",
"num":3,
"sites": [
{ "name":"demo01", "info":[ "A1111", "A2222", "A3333" ] },
{ "name":"demo02", "info":[ "B1111", "B2222", "B3333" ] },
{ "name":"demo03", "info":[ "C1111", "C2222" ] }
]
}
實現以下代碼,編寫一個get請求的案例,通過axios.get方式實現:
<template>
<div id="app">
{{info}}
</div>
</template>
<script>
import axios from "axios";
export default{
ele:'#app',
data(){
return{
info:null
}
},
mounted() {
axios
.get('../static/demo.json')
.then(response => (this.info = response))
.catch(function(error){
console.log(error)
})
}
}
</script>
<style>
</style>
上面例子中,我將整個返回對象 response 都展示出來,另外可以使用 response.data.sites 的方式獲取我要展示的數據:
axios
.get('../static/demo.json')
.then(response => (this.info = response.data.sites))
參數傳入方式:
//使用 URL 參數方式:
axios
.get('../static/demo.json?id=0001')
//使用 params 設置參數
axios
.get('../static/demo.json?id=0001',{
params: {
id: 0001
}
})
二、POST 方法
將 axios.get 改成 axios.post 即可:
axios
.post('../static/demo.json')
參數傳入方式:
axios
.post('../static/demo.json',
{
id: 0001, // 參數 id
name: 'zhangsan' // 參數 name
})
三、併發請求
多併發請求的實現方式如下:
function getID() {
return axios.get('/id/12345');
}
function getName() {
return axios.get('/name/zhangsan');
}
axios.all([getID(), getName()])
.then(axios.spread(function (acct, perms) {
// TODO 兩個請求都執行完成
}));
END.