关于“vue3 typescript封装axios过程示例”的完整攻略,以下是步骤:
一、安装依赖
-
在Vue3项目中,先安装vue3,使用命令:
npm install vue@next --save
-
安装typescript,使用命令:
npm install typescript --save-dev
-
安装axios,使用命令:
npm install axios --save
二、创建服务
-
在src目录下新建文件夹requests,创建requests.ts文件
-
在requests.ts文件中,引入axios,并为其创建实例
```typescript
import axios, { AxiosInstance } from 'axios';export class Requests {
private axiosInstance: AxiosInstance;constructor() {
this.axiosInstance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
});
}
}
```
三、封装请求方法
-
在requests.ts文件中,创建get方法,用于发送Get请求
```typescript
export class Requests {
...async get
(url: string, params?: any): Promise {
const response = await this.axiosInstance.get(url, { params });
return response.data;
}
}
``` -
创建post方法,用于发送Post请求
```typescript
export class Requests {
...async post
(url: string, data: any): Promise {
const response = await this.axiosInstance.post(url, data);
return response.data;
}
}
```
四、添加类型限制
-
在requests.ts文件中,定义请求的参数类型
```typescript
import { AxiosResponse } from 'axios';interface IUser {
id: number;
name: string;
email: string;
}interface IPost {
userId: number;
id: number;
title: string;
body: string;
}export class Requests {
...async getUser(id: number): Promise
> {
const response = await this.axiosInstance.get(/users/${id}
);
return response;
}async getPostsByUserId(userId: number): Promise
> {
const response = await this.axiosInstance.get(/posts?userId=${userId}
);
return response;
}async createPost(post: Omit
): Promise > {
const response = await this.axiosInstance.post('/posts', post);
return response;
}
}
``` -
用type方式限制response的返回类型
```typescript
export type ApiResponse= {
code: number;
message: string;
data: T;
}export class Requests {
...async getUser(id: number): Promise
> {
const response = await this.axiosInstance.get(/users/${id}
);
return response.data;
}async getPostsByUserId(userId: number): Promise
> {
const response = await this.axiosInstance.get(/posts?userId=${userId}
);
return response.data;
}async createPost(post: Omit
): Promise > {
const response = await this.axiosInstance.post('/posts', post);
return response.data;
}
}
```
以上就是“vue3 typescript封装axios过程示例”的完整攻略。
示例:
-
获取用户信息的代码示例
typescript
const requests = new Requests();
requests.getUser<IUser>(1).then((response) => {
console.log(response.data);
}).catch((error) => {
console.log(error);
}); -
创建一个帖子的代码示例
typescript
const requests = new Requests();
requests.createPost<IPost>({
title: 'hello',
body: 'hello world'
}).then((response) => {
console.log(response.data);
}).catch((error) => {
console.log(error);
});
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:vue3 typescript封装axios过程示例 - Python技术站