vue3+ts使用axios网络请求
时间: 2024-06-05 21:05:30 浏览: 142
Vue 3 + TypeScript 使用 Axios 进行网络请求的步骤如下:
1. 安装 Axios 库:在项目中安装 Axios 库,可以使用命令 `npm install axios --save` 或者 `yarn add axios`。
2. 创建 TypeScript 类型:定义 Axios 返回数据的类型,例如:
```typescript
interface ResponseData {
code: number;
message: string;
data: any;
}
```
3. 创建 Axios 实例:在 Vue 组件中创建 Axios 实例,例如:
```typescript
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ResponseData } from './types';
class ApiService {
private readonly axiosInstance: AxiosInstance;
constructor() {
this.axiosInstance = axios.create({
baseURL: 'https://example.com/api',
});
}
async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
const response: AxiosResponse<ResponseData<T>> = await this.axiosInstance.get<ResponseData<T>>(url, config);
return response.data.data;
}
async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
const response: AxiosResponse<ResponseData<T>> = await this.axiosInstance.post<ResponseData<T>>(url, data, config);
return response.data.data;
}
}
export default new ApiService();
```
4. 使用 Axios 实例:在 Vue 组件中使用 Axios 实例进行网络请求,例如:
```typescript
import { defineComponent, ref } from 'vue';
import ApiService from './apiService';
import { User } from './types';
export default defineComponent({
setup() {
const users = ref<User[]>([]);
const fetchUsers = async () => {
users.value = await ApiService.get<User[]>('/users');
};
return {
users,
fetchUsers,
};
},
});
```
相关问题:
1. 什么是 TypeScript?
2. 什么是 Axios?
3. 如何在 Vue 中使用 Axios 发送网络请求?
4. 如何处理 Axios 返回的数据?
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)