关于uni-app:uniapp数据请求封装

29次阅读

共计 956 个字符,预计需要花费 3 分钟才能阅读完成。

uni-app 数据申请封装

1. 开发环境 uni-app
2. 电脑系统 windows10 专业版
3. 在应用 uni-app 开发的过程中, 咱们会应用到数据申请, 上面我来分享一下,uni-app 数据申请封装, 心愿对你有所帮忙!
4. 和 pages 同级新增一个目录, 名字本人定义, 在这里我的名字是 chenhttp 在这个文件上面新建一个 chenhttp.js, 代码如下:

const BASE_URL='http://192.168.137.78:3000'; // 后盾接口地址
export const myRequest=(options)=>{return new Promise((resolve,reject)=>{
        uni.request({
            url:BASE_URL+options.url,
            method:options.method || 'GET', // 配置申请办法, 默认为 get 申请
            data:options.data || {},
            success:(res)=>{if(res.data.statusCode ==0){
                    return uni.showToast({title:'获取数据失败'})
                }
                resolve(res)
            },
            fail:(err)=>{
                uni.showToast({title:'申请接口失败'})
                reject(err)
            }
        })
    })
}

5. 为了方便使用, 咱们把这个办法挂载到全局, 在 main.js 中增加如下代码:

import {myRequest} from 'chenhttp/chenhttp.js';
Vue.prototype.$myRequest=myRequest;

6. 在 uni-app 模板中应用, 在 methods 中增加如下代码:

async chenget(){
                const res=await this.$myRequest({
                    url:'/feng', // 申请的接口
                    method:'post', // 申请办法
                    data:this.ChenindexconOnj // 传递的参数
                })
                console.log(res);  // 输入申请的数据
            }

7. 在 mounted 进行调用, 增加如下代码:

this.chenget();

8. 成果如下:

9. 后盾承受的参数, 成果为:

10. 本期的分享到了这里就完结啦, 是不是很 nice, 心愿对你有所帮忙, 让咱们一起致力走向巅峰!

正文完
 0