原文地址:https://www.jb51.net/article/177895.htm
本文實例講述了Vue學習之axios的使用方法。分享給大家供大家參考,具體如下:
Axios 是一個用於實現網絡數據請求的JavaScript庫,可以用在網頁和 node.js 中,用於創建 XMLHttpRequests,vue官方支持使用axios代替vue--resourse來實現網絡數據請求。
使用前需要在你的項目中安裝axios,例如通過npm安裝庫:
1
|
npm install --save axios
|
接着在項目中引入axios:
1
|
import axios from
'axios'
|
1、get請求
直接使用axios的全局變量來調用get方法,get中第一個參數傳遞url,第二個參數是相關配置,在其中可以傳遞params參數(參數以?形式加在url末尾),進行header的設置等。使用.then接收返回值,可以采用函數來處理返回結果res,其中res.data或者res.body是返回的數據。使用.catch捕獲異常,並可以打印錯誤信息參數error。
1
2
3
4
5
6
7
8
9
10
11
12
|
axios.get(
'data/zodiac.json'
,{
params:{
id:
"101"
},
header:{
token:
"axios"
}
}).then(res =>{
this
.msg=res.data;
}).
catch
(error =>{
console.log(error);
})
|
2、post請求
post方法調用、回掉、異常捕獲的使用與get類似。不同的是其參數分為三個,第一個是url地址,第二個是要傳遞的數據,第三個是傳輸選項配置。與get方法不同,post專門使用第二個參數進行數據傳遞,而不像get中將數據設置在配置選項params中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
axPost(){
axios.post(
'./data/test.php'
,
//url
{
//發送的數據
userId:
'105'
},
{
//option選項
headers:{
token:
"axPost"
}
}
).then(res =>{
//接收結果
this
.msg=res.data;
}).
catch
(err=>{
//處理錯誤
this
.msg=err;
})
}
|
3、HTTP請求
也可以直接使用http進行數據請求,直接進行url、method、data、headers、params等的設置,例如使用http發送post請求:
1
2
3
4
5
6
7
8
9
10
11
12
|
axios({
method:
"post"
,
data:{
userId:
"106"
},
headers:{
token:
"axHttp"
}
}).then(res=>{
this
.msg=res.data;
})
|
4、攔截器
axios也提供了在網絡請求發送前與數據返回時進行攔截的函數interceptors,以便進行相關處理。例如在發送前使用request.use攔截,進行你想要的執行的操作后再將config返回出去,在請求返回時使用response.use進行攔截,操作后再將結果返回:
1
2
3
4
5
6
7
8
|
axios.interceptors.request.use(config =>{
console.log(
"axois請求"
);
return
config;
});
axios.interceptors.response.use(res =>{
console.log(
"axois回調"
);
return
res;
})
|