mpvue 封装请求数据
时间: 2023-08-07 20:01:40 浏览: 59
对于封装请求数据,你可以使用 `mpvue` 的 `wx.request` 方法来发送请求。下面是一个简单的封装示例:
1. 创建一个 `api.js` 文件,用于封装请求方法:
```js
import { baseUrl } from './config'
export const request = (url, method = 'GET', data = {}) => {
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + url,
method,
data,
success: res => {
resolve(res.data)
},
fail: err => {
reject(err)
}
})
})
}
```
2. 在需要发送请求的页面或组件中,引入 `api.js` 并调用封装好的请求方法:
```js
import { request } from '@/api'
// 发送 GET 请求示例
request('/api/users')
.then(res => {
console.log(res)
})
.catch(err => {
console.error(err)
})
// 发送 POST 请求示例
request('/api/login', 'POST', { username: 'admin', password: '123456' })
.then(res => {
console.log(res)
})
.catch(err => {
console.error(err)
})
```
在上述示例中,`baseUrl` 是你的 API 接口的基础 URL,可以根据实际情况进行修改。`request` 方法接受三个参数:`url` 表示请求的相对路径,`method` 表示请求的方法(默认为 GET),`data` 表示请求的数据(默认为空对象)。该方法返回一个 Promise 对象,可以通过 `then` 和 `catch` 方法处理请求成功和失败的回调。
这样,你就可以使用 `mpvue` 封装请求数据了。当然,你也可以根据实际需求对封装的方法进行进一步优化和扩展。
相关推荐
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)