Vue3中的Axios封装

1. Composition API风格的封装
Vue3推荐使用Composition API进行更灵活的封装:
// src/composables/useApi.js
import { ref } from 'vue';
import service from '@/api/axios';
export function useApi() {
const loading = ref(false);
const error = ref(null);
const data = ref(null);
const execute = async (apiCall, ...args) => {
loading.value = true;
error.value = null;
try {
const response = await apiCall(...args);
data.value = response;
return response;
} catch (err) {
error.value = err;
throw err;
} finally {
loading.value = false;
}
};
return {
loading,
error,
data,
execute
};
}
2. 基于Vue3的拦截器优化
// src/api/axios.js
import axios from 'axios';
import { getCurrentInstance } from 'vue';
const service = axios.create({
baseURL: import.meta.env.VITE_BASE_API,
timeout: 10000
});
// 请求拦截器 - 支持响应式
service.interceptors.request.use(config => {
const instance = getCurrentInstance();
if (instance) {
// 可在组件内触发事件
instance.emit('request-start');
}
// 自动添加token
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
3. TypeScript支持
对于TypeScript项目,可以增强类型安全:
// src/types/api.ts
export interface ApiResponse<T = any> {
code: number;
message: string;
data: T;
}
export interface PageParams {
page: number;
limit: number;
sort?: string;
}
// 封装带类型的API调用
export class ApiClient {
constructor(private http = service) {}
async get<T>(url: string, config?: any): Promise<ApiResponse<T>> {
const response = await this.http.get<ApiResponse<T>>(url, config);
return response.data;
}
async post<T>(url: string, data?: any, config?: any): Promise<ApiResponse<T>> {
const response = await this.http.post<ApiResponse<T>>(url, data, config);
return response.data;
}
}
4. Vue3组件中使用示例
<template>
<div>
<!-- 加载状态 -->
<div v-if="loading" class="loading">加载中...</div>
<!-- 错误状态 -->
<div v-if="error" class="error">
请求失败: {{ error.message }}
</div>
<!-- 数据展示 -->
<div v-if="data">
<div v-for="user in data" :key="user.id">
{{ user.name }}
</div>
</div>
<button @click="fetchUsers" :disabled="loading">
获取用户列表
</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { userAPI } from '@/api';
import { useApi } from '@/composables/useApi';
const { loading, error, data, execute } = useApi();
const fetchUsers = async () => {
try {
await execute(userAPI.getList);
} catch (err) {
console.error('获取用户列表失败', err);
}
};
</script>

高级封装技巧
1. 请求重试机制
// 请求重试拦截器
service.interceptors.response.use(undefined, async (error) => {
const config = error.config;
// 如果未设置重试次数,默认3次
if (!config.retry) config.retry = 3;
if (config.retry > 0) {
// 指数退避重试
const delay = Math.pow(2, 3 - config.retry) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
config.retry -= 1;
return service(config);
}
return Promise.reject(error);
});
2. 请求取消功能
// 请求取消封装
const pendingRequests = new Map();
export const addPendingRequest = (config) => {
const url = `${config.url}&${config.method}&${JSON.stringify(config.params)}`;
config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
if (!pendingRequests.has(url)) {
pendingRequests.set(url, cancel);
}
});
};
export const removePendingRequest = (config) => {
const url = `${config.url}&${config.method}&${JSON.stringify(config.params)}`;
if (pendingRequests.has(url)) {
const cancel = pendingRequests.get(url);
cancel(url);
pendingRequests.delete(url);
}
};
3. 缓存策略实现
// 请求缓存
const cacheMap = new Map();
export const withCache = (apiCall, cacheKey, ttl = 5 * 60 * 1000) => {
return async (...args) => {
const now = Date.now();
const cached = cacheMap.get(cacheKey);
if (cached && now - cached.timestamp < ttl) {
return Promise.resolve(cached.data);
}
const result = await apiCall(...args);
cacheMap.set(cacheKey, {
data: result,
timestamp: now
});
return result;
};
};
环境配置与最佳实践
1. 多环境配置
// 环境切换配置
let baseURL = '';
if (process.env.NODE_ENV === 'development') {
baseURL = 'https://dev-api.example.com';
} else if (process.env.NODE_ENV === 'test') {
baseURL = 'https://test-api.example.com';
} else if (process.env.NODE_ENV === 'production') {
baseURL = 'https://api.example.com';
}
const service = axios.create({
baseURL,
timeout: 10000
});
2. 错误处理最佳实践
// 统一错误处理
const handleError = (error) => {
if (axios.isCancel(error)) {
console.log('请求被取消', error.message);
return;
}
const errorInfo = {
message: error.message,
code: error.response?.status,
url: error.config?.url
};
// 根据错误类型进行不同处理
if (error.response?.status >= 500) {
// 服务器错误
showServerError(errorInfo);
} else if (error.response?.status === 401) {
// 未授权
redirectToLogin();
} else {
// 其他错误
showCommonError(errorInfo);
}
return Promise.reject(error);
};
总结
Axios封装在Vue项目开发中至关重要,良好的封装能够:
- 提高代码复用性:统一请求处理逻辑
- 增强可维护性:集中管理接口和配置
- 统一错误处理:规范化异常情况处理
- 优化开发体验:提供类型支持和智能提示
Vue2与Vue3封装差异:
- Vue2更多依赖Options API和全局配置
- Vue3推荐使用Composition API和响应式封装
- Vue3更好的TypeScript集成支持
建议:在实际项目中,根据团队技术栈和项目需求选择合适的封装方案,并建立统一的编码规范,确保所有开发者遵循相同的请求处理模式。
立即在你的Vue项目中实践这些封装技巧,可以从基础的拦截器配置开始,逐步完善错误处理、缓存策略等高级功能,这将显著提升你的开发效率和代码质量。
1709

被折叠的 条评论
为什么被折叠?



