帮我用vue3和ts封装一个axios
时间: 2024-03-11 14:19:42 浏览: 95
以下是一个简单的使用Vue3和TypeScript封装Axios的示例:
1. 安装依赖
```bash
npm install axios
npm install @types/axios
```
2. 创建一个`api.ts`文件
```typescript
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
export interface ApiResponse<T> {
code: number;
message: string;
data: T;
}
class Api {
private axiosInstance: AxiosInstance;
constructor() {
this.axiosInstance = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
});
this.axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => {
// 在请求发送之前做一些处理
return config;
});
this.axiosInstance.interceptors.response.use((response: AxiosResponse) => {
// 对响应数据做一些处理
return response;
}, (error) => {
// 对响应错误做一些处理
return Promise.reject(error);
});
}
public async get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
const response = await this.axiosInstance.get<T>(url, config);
return response.data;
}
public async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
const response = await this.axiosInstance.post<T>(url, data, config);
return response.data;
}
public async put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
const response = await this.axiosInstance.put<T>(url, data, config);
return response.data;
}
public async delete<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
const response = await this.axiosInstance.delete<T>(url, config);
return response.data;
}
}
export default new Api();
```
3. 在Vue组件中使用
```vue
<template>
<div>
<button @click="getData">Get Data</button>
<ul>
<li v-for="item in data" :key="item.id">{{ item.name }} - {{ item.email }}</li>
</ul>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import api, { ApiResponse } from './api';
interface User {
id: number;
name: string;
email: string;
}
export default defineComponent({
name: 'App',
setup() {
const data = ref<User[]>([]);
const getData = async () => {
const response: ApiResponse<User[]> = await api.get('/users');
data.value = response.data;
};
return {
data,
getData,
};
},
});
</script>
```
在上面的示例中,我们首先创建了一个`Api`类,它封装了Axios的所有HTTP请求方法,并添加了请求和响应拦截器。然后,在Vue组件中引入该类并调用其方法来发起HTTP请求,最后将响应数据绑定到组件的数据属性中。
阅读全文