Vue3 axios数据请求封装
环境:vue3+ts+vite
首先在项目目录下安装axios
运行 npm install axios
成功后在package.json文件会显示。
目录:
request.ts文件代码:
import axios from 'axios'
const request= axios.create({
baseURL:'https://api.xxxxx.com',//请求地址
timeout: 60000, // 请求超时时间
withCredentials: true,// 异步请求携带cookie
headers: {
//设置后端需要的传参类型
'Content-Type': 'application/json',
},
})
// 添加请求拦截器
request.interceptors.request.use(config=>{
// 如果你要去localStor获取token,(如果你有)
// let token = localStorage.getItem("x-auth-token");
// if (token) {
//添加请求头
//config.headers["Authorization"]="Bearer "+ token
// }
return config
},err=>{
return Promise.reject(err)
});
// 添加响应拦截器
request.interceptors.response.use(response=>{
return response.data
},err=>{
return Promise.reject(err)
});
export default request
api.ts文件代码:
import instance from "./request";
const api_name = "/api/v1";
export default {
getData(url: string, params: object) {
return instance({
url: api_name+url,
method: 'get',
params
})
},
postData(url: string, params: object){
return instance({
url: api_name+url,
method: 'post',
data: params,
})
}
}
使用:
<template>
<div class="news">
<ul>
<li v-for="item in state.list">
{{item.title}}
</li>
</ul>
</div>
</template>
<script setup lang="ts">
import {reactive} from "vue";
import getApi from "@/utils/api";
import {useRoute} from "vue-router";
const route=useRoute()
const state=reactive({
list:<any>[]
})
getApi.getData("/content/news/",route.query).then((res)=>{
state.list=res.data.list
console.log(res)
})
</script>