原文地址: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;
})
|