我是靠谱客的博主 尊敬心情,这篇文章主要介绍uniapp如何封装request请求,现在分享给大家,希望可以做个参考。

本教程操作环境:windows7系统、uni-app2.5.1版本、thinkpad t480电脑。

推荐(免费):uni-app开发教程

uniapp封装request请求的方法:

1、项目下新建common文件夹,再创建request.js文件

586ee9a55ade2f47cad57f7129e6973.png

2、打开request.js文件,开始写封装的代码

思路很简单

  • 定义域名:baseUrl;

  • 定义方法:api;

通过promise异步请求,最后导出方法。

request.js参考代码如下

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const baseUrl = 'https://unidemo.dcloud.net.cn' const request = (url = '', date = {}, type = 'GET', header = { }) => { return new Promise((resolve, reject) => { uni.request({ method: type, url: baseUrl + url, data: date, header: header, dataType: 'json', }).then((response) => { setTimeout(function() { uni.hideLoading(); }, 200); let [error, res] = response; resolve(res.data); }).catch(error => { let [err, res] = error; reject(err) }) }); } export default request
登录后复制

3、在main.js全局注册

复制代码
1
2
import request from 'common/request.js' Vue.prototype.$request = request
登录后复制

a123546200accbd76c65b54636da05c.png

4、页面调用

复制代码
1
2
3
4
5
6
this.$request('/api/news', { // 传参参数名:参数值,如果没有,就不需要传 }).then(res => { // 打印调用成功回调 console.log(res) })
登录后复制

页面调用的index.vue

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<template> <view> <uni-list v-for="(item,index) in productList" :key="index"> <uni-list-item :title="item.author_name" :note="item.title"></uni-list-item> </uni-list> </view> </template> <script> import uniList from "@/components/uni-list/uni-list.vue" import uniListItem from "@/components/uni-list-item/uni-list-item.vue" export default { components: { uniList, uniListItem }, data() { return { productList: [], }; }, onLoad() { this.getList(); }, methods: { getList() { this.$request('/api/news', { // 传参参数名:参数值,如果没有,就不需要传 // "username": "john", // "key": this.searchValue }).then(res => { // 打印调用成功回调 console.log(res) this.productList = res; }) }, } } </script> <style> </style>
登录后复制

以上就是uniapp如何封装request请求的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是尊敬心情最近收集整理的关于uniapp如何封装request请求的全部内容,更多相关uniapp如何封装request请求内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部