在vue3.0面世后作者就即时宣布将不再对vue-resource更新了,这也就意味着它逐渐被放弃,axios取而代之。axios同样是异步请求数据,但是基于promise实现。
一. 项目安装
在项目中终端输入指令:
npm install axios --save
在需要请求数据的文件中引入axios:
import axios from "axios"
二. 使用方式
方法一: 当需要多个请求接口,推荐采用方法一。
const myAxios = axios.create({
baseURL: "https://tianqiapi.com", //接口基础地址
timeout: 3000, //允许延迟时长
headers: {'Content-Type':'application/x-www-form-urlencoded'} //post请求头部,默认将请求数据作json向后端传送;多数情况后端希望是"x-www-form-urlencoded"格式。大家视实际情况而变。
})
myAxios.get("/api?version=v6&appid=xxx&appsecret=xxx")
.then((res) => {
const data = res.data;
......
})
.catch((error) => {
console.log(error);
}
get请求也可以有params
写法:
myAxios.get("/api", {
params: {
version: 'v6',
appid: 'xxx',
appsecret: 'xxx'
}
}).
post请求基础写法:
myAxios.post("/api", {
data: {
version: 'v6',
appid: 'xxx',
appsecret: 'xxx'
}
}).
方法二: 当只需要一个请求接口时,推荐采用方法二。
axios.create({
baseURL: "https://tianqiapi.com",
timeout: 3000,
headers: {'Content-Type':'application/x-www-form-urlencoded'}
})
axios.get("/api?version=v6&appid=xxx&appsecret=xxx")
.then((res) => {
const data = res.data;
......
})
.catch((error) => {
console.log(error);
}
方法三: 全局配置,存在优先级。
//全局配置axios属性
axios.default.timeout = 5000;
axios.default.headers = {'Content-Type':'application/x-www-form-urlencoded'}
//创建请求接口实例,配置该实例属性
const myAxios = axios.create({
baseURL: "https://tianqiapi.com",
timeout: 3000, //该实例的timeout
})
//发送请求,配置该请求属性
myAxios.get("/api",{
params: {
version: 'v6',
appid: 'xxx',
appsecret: 'xxx'
},
timeout: 1000) //该请求的timeout
.then((res) => {
const data = res.data;
......
})
.catch((error) => {
console.log(error);
}
配置优先级:全局 < 实例 < 请求
全局配置会为所有请求接口配置默认的属性值,当接口实例内没有设置该属性时,将采用全局配置;但当接口实例设置了该属性,则将覆盖全局配置,同理,发送请求的配置也会覆盖接口实例的配置。所以在上面的例子中,最终的请求timeout为1000。
三. 小结
关于在vue中安装使用axios获取数据的日常操作基本就是这些,在方法一中我也是用代码展示了get和post的基本用法,至于axios的详细介绍和完整配置属性这里就不做无谓的复制了,请移步到axios官方中文文档学习:http://www.axios-js.com/