小程序公共方法封装(app.js 源码分享)

封装一个好的功能集(全局方法库),能更好的保证代码的一致性和工作的高效。

下面是小编经过几次小程序项目经验累计的原创功能集,能满足大部分功能需求。有其它需求望开发者们自行添加和修改

小编还有话说:

  1. request 请求方法未使用 ES6 中的 Promise。大部分情况下都可以不使用 Promise,毕竟真正的多次回调的情况还是少数的。有需求的可自行通过增加Promise来解决。
  2. getElementData 获取元素自定义属性方法是非常非常实用的,在小程序中多多使用 data-* 是非常有必要的。
  3. 请求数据作为最关键的方法,在文章的尾部有源码提供,请往下看哦!

app.js

/**
 * 小程序全局方法参考
 * 作者:helang
 * 邮箱:[email protected]
 * QQ:1846492969
**/

App({
    globalData: {
        isIphoneX: false
    },
    onLaunch: function () {
        /* 将是否iphoneX 信息缓存到全局公众数据中 */
        this.globalData.isIphoneX = this.isIphoneX();
    },
    /* iphoneX兼容 */
    isIphoneX() {
        let mobile = wx.getSystemInfoSync();
        if (mobile.model.indexOf("iPhone X") >= 0) {
            return true;
        } else {
            return false;
        }
    },
    /* 常用正则表达式集 */
    regExps: {
        email: /^[0-9a-zA-Z_]+@[0-9a-zA-Z_]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$/,    //邮箱
        mobile: /^(?:1\d{2})-?\d{5}(\d{3}|\*{3})$/,    //手机号码
        qq: /^[1-9][0-9]{4,9}$/,    //QQ
        befitName: /^[a-z0-9A-Z\u4e00-\u9fa5]+$/,    //合适的用户名,中文,字母,数字
        befitPwd: /^[a-z0-9A-Z_]+$/,     //合适的用户名,字母,数字,下划线
        allNumber: /^[0-9]+.?[0-9]$/    //全部为数字
    },
    /*获取元素自定义属性-当前事件元素 */
    getElementData(el, name) {
        if (name) {
            return el.currentTarget.dataset[name];
        } else {
            return el.currentTarget.dataset;
        }
    },
    /*获取元素大小及位置 */
    getElementRect(select, callBack) {
        wx.createSelectorQuery().select(select).boundingClientRect(function (rect) {
            callBack && callBack(rect);
        }).exec();
    },
    /*信息提示 */
    showToast(title = "未知错误,请重试!", icon = "none", duration = 2000) {
        wx.showToast({
            title: title,
            icon: icon,
            duration: duration,
            mask: true
        });
    },
    /*加载提示 */
    showLoading(title = "正在加载") {
        wx.showLoading({
            title: title,
            mask: true
        });
    },
    /*请求地址*/
    requestUrl: "https://wxapi.xxx.com",
    /*发送请求 */
    request(param = {}, successFn, failFn) {
        wx.request({
            "url": this.requestUrl + param.url,
            "method": param.method || "POST",
            "data": param.data || {},
            "success": (res) => {
                if (res.statusCode == 200) {
                    successFn && successFn(res.data);
                } else {
                    wx.hideLoading();
                    this.showToast("请求失败,请重试!");
                }
            },
            "fail": () => {
                wx.hideLoading();
                if (failFn) {
                    failFn();
                } else {
                    this.showToast("网络错误!请重试!");
                }
            }
        });
    },
    /*上传文件地址*/
    uploadFileUrl: "https://imgupload.xxx.com",
    /* 上传文件
    *  files : 文件路径
    */
    uploadFile(files, callFn) {
        wx.uploadFile({
            url: this.uploadFileUrl,
            filePath: files,
            name: 'file',
            formData: {	// 这里的数据一般都为固定的,请根据自己的业务需求修改
                "UserID": '用户ID',
                "Token": '用户令牌'
            },
            success: (res) => {
                if (res.statusCode == 200) {
                    callFn && callFn(res.data);
                } else {
                    wx.hideLoading();
                    this.showToast("上传失败,请重试!");
                }
            },
            fail: () => {
                wx.hideLoading();
                this.showToast("上传失败,请重试!");
            }
        });
    },
    /* 获取上一页路由
     * 这个很重要,处理上一个路由栈
    */
    getPrevPage() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        return prevPage;
    },
    /* 关闭当前页面 */
    closePage() {
        wx.navigateBack({
            delta: 1
        });
    },
    /*获取随机数*/
    getRandom(min, max) {
        return Math.floor(Math.random() * (max - min)) + min + 1;
    }
})

request 请求方法,使用示例

/* 获取到小程序全局唯一的 App 实例。
 * 建议在 pages/*.js 的头部引用,引用一次多次使用,避免滥用 getApp() 函数
*/
const app=getApp();

/* 使用全局 request 请求方法 */
app.request({
    "url":'/list',      // 请求地址,必需的
    "method":"GET",     // 提交方式,默认POST,默认时可省略
    "data":{"a":"1"}    // 提交数据,默认undefined,不需要提交数据时可省略
},(res)=>{
    //请求成功的回调函数
    console.log(res);
},()=>{
    //请求失败的回调函数,不需要时可省略
})

作者:黄河爱浪 QQ:1846492969,邮箱:[email protected]

微信公众号:web-7258,本文原创,著作权归作者所有,转载请注明原链接及出处。

更多精彩文章,请扫下方二维码关注我的公众号

你可能感兴趣的:(小程序)