axios接口的使用
配置axios
npm i axios -S
一、基础方法
①创建@src/utils/request.js,封装
import axios from 'axios'
const request = axios.create({
// 指定请求根路径
baseURL:'https://www.escook.cn'
})
export default request
②在myHome组件中封装initArticle方法
导入并写方法
<script>
import request from "@/utils/request";
export default {
name: "myHome",
data() {
return {
page: 1,
limit: 10,
};
},
created() {
this.initArticleList();
},
methods: {
async initArticleList() {
const { data: res } = await request.get("/articles", {
params: {
_page: this.page,
_limit: this.limit,
},
});
console.log(res);
},
},
};
</script>
二、改进:封装成articleAPI模块
如果每一个组件都要进行访问资源,代码重复太多。
①创建@src/utils/request.js,封装
import axios from 'axios'
const request = axios.create({
// 指定请求根路径
baseURL:'https://www.escook.cn'
})
export default request
②配置@/api/articleAPI
// 文章相关的API接口
import request from "@/utils/request"
export const getArticleAlistAPI = function(_page,_limit) {
return request.get("/articles", {
params: {
_page,
_limit
}
})
}
③myHome.vue中调用
<script>
// import request from "@/utils/request";不再导入request模块
import { getArticleAlistAPI } from "@/api/articleAPI";
//简便的调用方法
const result = getArticleAlistAPI(1,5)
console.log(result);
</script>
再将promise解构
三、最终总结
①创建@src/utils/request.js,封装
import axios from 'axios'
const request = axios.create({
// 指定请求根路径
baseURL:'https://www.escook.cn'
})
export default request
②配置@/api/articleAPI
// 文章相关的API接口
import request from "@/utils/request"
export const getArticleAlistAPI = function(_page,_limit) {
return request.get("/articles", {
params: {
_page,
_limit
}
})
}
③在组件中导入API,
不再在组件中导入requet。
在created()中调用initArticleList(),initArticleList()方法去调用getArticleAlistAPI(this.page,this.limit)从而得到数据
<script>
import { getArticleAlistAPI } from '@/api/articleAPI';
export default {
name: "myHome",
data() {
return {
page: 1,
limit: 10,
};
},
created() {
this.initArticleList();
},
methods: {
async initArticleList() {
const {data:res} = await getArticleAlistAPI(this.page,this.limit)
console.log(res);//调用测试
}
},
};
</script>
标签:axios,const,request,接口,limit,使用,import,page
From: https://www.cnblogs.com/tupo/p/17215645.html