vue3中使用ts封装axios给出代码
时间: 2024-05-01 09:18:23 浏览: 164
当然,我非常乐意回答你的问题!以下是一个使用 TypeScript 封装 Axios 的 Vue3 代码示例:
```
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { reactive } from 'vue';
interface ResponseData<T = any> {
code: number;
message: string;
data: T;
}
export interface Result<T = any> {
loading: boolean;
error: string;
response: ResponseData<T> | null;
fetchData: (axiosConfig?: AxiosRequestConfig) => Promise<void>;
}
export function useAxios<T = any>(url: string, axiosConfig: AxiosRequestConfig = {}): Result<T> {
const state = reactive({
loading: false,
error: '',
response: null,
fetchData: async (axiosConfig?: AxiosRequestConfig) => {
state.loading = true;
try {
const response: AxiosResponse<ResponseData<T>> = await axios.request({
url,
...axiosConfig,
});
state.response = response.data;
} catch (error) {
state.error = error.message;
} finally {
state.loading = false;
}
},
});
state.fetchData(axiosConfig);
return state;
}
```
希望这个代码示例可以帮到你!
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)