vue3 接口请求封装
时间: 2023-09-19 15:11:13 浏览: 65
Vue 3 中接口请求的封装有多种方式,下面我会介绍一种常见的方法:
首先,我们可以创建一个独立的模块,专门用于发送接口请求。这个模块可以是一个单独的文件,比如 `api.js`。
```javascript
import axios from 'axios';
const api = axios.create({
baseURL: 'http://api.example.com', // 接口请求的基础 URL
timeout: 5000, // 请求超时时间
});
export function fetchUser(userId) {
return api.get(`/user/${userId}`);
}
export function updateUser(userId, data) {
return api.put(`/user/${userId}`, data);
}
// 其他接口请求方法...
```
然后,在需要使用接口的地方,我们可以导入上面定义的方法,并调用它们来发送请求。
```javascript
import { fetchUser, updateUser } from './api';
export default {
data() {
return {
user: null,
};
},
methods: {
async getUser(userId) {
try {
const response = await fetchUser(userId);
this.user = response.data;
} catch (error) {
console.error(error);
}
},
async updateUser(userId, data) {
try {
await updateUser(userId, data);
// 更新成功的处理逻辑...
} catch (error) {
console.error(error);
}
},
// 其他接口请求方法...
},
};
```
上述代码中,我们使用了 axios 库来发送实际的请求。你可以根据项目需求选择其他库或自己封装一个请求库。
需要注意的是,上述代码只是一个简单的示例,实际项目中可能还需要处理请求的错误、loading 状态、请求拦截器、响应拦截器等等。具体的封装方式可以根据项目的需求进行调整和扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)