封装一个axios+vue3+ts的ajax请求
时间: 2023-09-08 14:10:17 浏览: 183
以下是一个基于Axios、Vue3和TypeScript的Ajax请求封装示例:
```
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { reactive } from 'vue';
interface ResponseData {
code: number;
message: string;
data: any;
}
interface AxiosResult<T> {
data: T | null;
error: string | null;
loading: boolean;
}
class AjaxService {
private instance: AxiosInstance;
constructor(baseURL: string) {
this.instance = axios.create({
baseURL,
timeout: 5000,
});
this.instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
config.headers.Authorization = sessionStorage.getItem('token') || '';
return config;
},
(error: any) => {
console.error(error);
},
);
this.instance.interceptors.response.use(
(res: AxiosResponse<ResponseData>) => {
if (res.status === 200) {
if (res.data.code === 0) {
return res.data.data;
} else {
console.error(res.data.message);
return null;
}
} else {
console.error(res.status);
return null;
}
},
(error: any) => {
console.error(error);
return null;
},
);
}
public async get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResult<T>> {
const result: AxiosResult<T> = reactive({
data: null,
error: null,
loading: true,
});
try {
const response = await this.instance.get(url, config);
result.data = response;
} catch (error) {
result.error = error;
} finally {
result.loading = false;
}
return result;
}
public async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResult<T>> {
const result: AxiosResult<T> = reactive({
data: null,
error: null,
loading: true,
});
try {
const response = await this.instance.post(url, data, config);
result.data = response;
} catch (error) {
result.error = error;
} finally {
result.loading = false;
}
return result;
}
}
export default new AjaxService('https://example.com/api');
```
使用示例:
```
import ajax from './ajax-service';
const result = await ajax.get<User[]>('/users');
if (result.error) {
console.error(result.error);
} else if (result.data) {
console.log(result.data);
} else {
console.log('No data returned.');
}
```
阅读全文