vue3+typscript封装axios
时间: 2023-08-27 08:06:15 浏览: 107
好的,下面是一个简单的vue3+typescript封装axios的示例:
```typescript
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
interface ResponseData {
code: number;
data: any;
message: string;
}
class HttpClient {
private readonly instance: AxiosInstance; // axios实例
constructor(baseURL: string) {
this.instance = axios.create({
baseURL,
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
});
this.instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
// 可以在请求头中添加一些公共的参数,例如token
// config.headers['Authorization'] = 'Bearer ' + token;
return config;
},
(error: any) => {
return Promise.reject(error);
}
);
this.instance.interceptors.response.use(
(response: AxiosResponse<ResponseData>) => {
const { code, data, message } = response.data;
if (code !== 0) {
// 这里可以根据后端返回的错误码进行一些统一的处理
throw new Error(message);
}
return data;
},
(error: any) => {
return Promise.reject(error);
}
);
}
public async get<T>(url: string, params?: any): Promise<T> {
const response = await this.instance.get<ResponseData>(url, { params });
return response.data.data;
}
public async post<T>(url: string, data?: any): Promise<T> {
const response = await this.instance.post<ResponseData>(url, data);
return response.data.data;
}
public async put<T>(url: string, data?: any): Promise<T> {
const response = await this.instance.put<ResponseData>(url, data);
return response.data.data;
}
public async delete<T>(url: string, params?: any): Promise<T> {
const response = await this.instance.delete<ResponseData>(url, { params });
return response.data.data;
}
}
export default HttpClient;
```
然后在你的Vue组件中使用:
```typescript
import { defineComponent, ref } from 'vue';
import HttpClient from '@/utils/http-client';
export default defineComponent({
setup() {
const httpClient = new HttpClient('https://api.example.com');
const isLoading = ref(false);
const data = ref(null);
const error = ref(null);
const fetchData = async () => {
isLoading.value = true;
try {
data.value = await httpClient.get('/user/info', { id: 1 });
} catch (err) {
error.value = err.message;
} finally {
isLoading.value = false;
}
};
return { isLoading, data, error, fetchData };
}
});
```
以上示例仅供参考,具体的实现可能需要根据你的项目进行一些调整。
阅读全文