能不能写个vue3的关于TYPESCIPT的axios封装
时间: 2023-01-11 09:55:36 浏览: 132
可以的。下面是一个示例:
```
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Promise } from 'es6-promise';
interface IResponse<T = any> extends AxiosResponse {
data: T;
}
export default class HttpClient {
private static instance: HttpClient;
public static getInstance(): HttpClient {
if (!HttpClient.instance) {
HttpClient.instance = new HttpClient();
}
return HttpClient.instance;
}
public request<T = any>(config: AxiosRequestConfig): Promise<IResponse<T>> {
return axios.request<T>(config);
}
public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<IResponse<T>> {
return axios.get<T>(url, config);
}
public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<IResponse<T>> {
return axios.delete(url, config);
}
public head<T = any>(url: string, config?: AxiosRequestConfig): Promise<IResponse<T>> {
return axios.head(url, config);
}
public options<T = any>(url: string, config?: AxiosRequestConfig): Promise<IResponse<T>> {
return axios.options(url, config);
}
public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<IResponse<T>> {
return axios.post<T>(url, data, config);
}
public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<IResponse<T>> {
return axios.put<T>(url, data, config);
}
public patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<IResponse<T>> {
return axios.patch<T>(url, data, config);
}
}
```
使用方法:
```
import HttpClient from './httpClient';
const http = HttpClient.getInstance();
http.get('/users').then(response => {
console.log(response.data);
});
```
注意:这只是一个示例,在实际使用中可能需要根据自己的需求进行修改。
阅读全文