分享:vue3使用async/await(异步同步化)将axios封装请求api管理
2024-10-21 20:34:09
分享如何在Vue3中使用async/await异步编程方法,将axios封装成一个通用的请求管理模块。通过这种方法,不仅能简化代码结构,还能增强代码的可读性和维护性。文章将详细介绍从创建axios实例、添加请求和响应拦截器,到实现统一的错误处理和请求重试策略的完整过程,为开发者提供一套高效、优雅的API管理方案。希望能帮助大家更好地管理项目中的API请求,提高开发效率。
一、创建vue项目后,安装axios模块
bash
npm install axios --save
二、在路径src/assets目录创建axios.js文件,内容如下:
Javascript
import axios from "axios";
import router from "@/router";
const apiClient = axios.create({
baseURL: "https://api.example.com",
timeout: 30 * 1000,
headers: { "Content-Type": "application/json"},
});
let cancelToken;
const requestWithCancel = async (url, method = "POST", data = {}) => {
let result = {};
const member = JSON.parse(localStorage.getItem("member"));
const token = member?.token ?? "";
apiClient.defaults.headers["Authorization"] = token;
// 如果上一个请求存在,则取消上一个请求
if (cancelToken) {
cancelToken.cancel();
}
// 为当前请求创建一个新的取消令牌
cancelToken = axios.CancelToken.source();
try {
const response = await apiClient({
method,
url,
data,
cancelToken: cancelToken.token,
});
result = response.data;
} catch (error) {
if (!axios.isCancel()) {
result = { code: 0, msg: error.message || error };
}
}
// 根据result的不同code给出不同的消息弹窗
if (result.msg) {
const type = result.code === 200 ? "success" : "error";
const duration = result.code === 200 ? 1500 : 3000;
ElNotification({ message: result.msg, type, duration });
if (result.code === 1001) {
localStorage.removeItem("member");
router.replace({ name: "login" });
}
}
return result;
};
//下面具体数据获取再次封装,是为了不在vue页面中写api地址,防止以后有更改方便在axios文件统一修改,实际应用中可自行斟酌!
// 获取文章列表
export const queryArticleList = async () => {
return await requestWithCancel("/articlelist");
};
三、在vue页面中调用封装的方法:
Vue
<script setup>
import { queryArticleList } from "../../assets/axios";
const GetTableData = async () => {
const result = await queryArticleList();
console.log(result);
};
</script>
<template>
<div>
<button @click="GetTableData">queryData</button>
</div>
</template>
End