小程序常用的一些公用方法封装

1、ajax请求

const wxPromisify = fn => (obj = {}) => new Promise((resolve, reject) => {
    obj.success = res => resolve(res) // 成功(可在里面加处理,如登录超时等)
    obj.fail = res => reject(res) // 失败
    fn(obj)
})
const ajaxFns = (url, data, method, contentType) => wxPromisify(wx.request)({
    url: url,
    data:data,
    method: method ? method : 'POST',
    header: {
    cookie: getApp().globalData.token ? getApp().globalData.token : '',
    'content-type': contentType ? contentType : 'application/x-www-form-urlencoded'
    }
})
例子:ajaxFns(url,data,method,contentType).then(res=>{})

 

2、时间格式转换

const formatTime = (date, type) => {
    let year = date.getFullYear()//年
    let month = date.getMonth() + 1//月
    let day = date.getDate()//日
    let hour = date.getHours()//时
    let minute = date.getMinutes()//分
    let second = date.getSeconds()//秒
    let getMilliseconds = date.getMilliseconds()//毫秒
    if (type == 1) { //2019-12-12 12:12:12
        return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
    } else if (type == 2) { //2019年12月12日
        if (month < 10) month = '0' + month
        if (day < 10) day = '0' + day
        return year + '年' + month + '月' + day + '日'
    } else if (type == 3) { //时间戳 123456789
        return date.getTime()
    }
}
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
例子:formatTime(new Date(), type)

3、页面跳转

const gotoPage = (url, param) => {
    wx.navigateTo({ url: parseUrl(url, param) })
}
例子:gotoPage(url,{param:param})
const gotoTab = (url, param) => {
    wx.reLaunch({ url: parseUrl(url, param) })
}
例子:gotoTab(url,{param:param})
const backPage = (val) => { //返回堆栈上级页面层数 注:redirectTo页面不会将页面加入堆栈
    wx.navigateBack({ delta: val })
}
例子:backPage(num)//返回几层就输多少
const parseUrl = (url, param) => {
    if (typeof(param) !== "object") return url
    var str = ''
    for (let i in param) {
        str += ('&' + i + '=' + param[i])
    }
    if (url.indexOf('?') > -1) {
        return url + str
    } else {
        return url + '?' + str.substr(1)
    }
}

4、排序

const sortFns = (arr, param) => {//数组 排序参数
    return arr.sort(compare(param))
}
const compare = (property) => {
    return (a, b) => {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
    }
}
例子:sortFns(arr,'param')

5、缓存

const setStorage = (key, data) => { //存
    wx.setStorageSync(key, data)
}
const getStorage = (key) => { //取
    return wx.getStorageSync(key)
}
const removeStorage = (key) => { //删
    wx.removeStorageSync(key)
}

6、url截取参数

const getUrlParam = (url, param) => {
    let reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    let index = url.indexOf("?")
    let r = url.substring(index).substr(1).match(reg) //匹配目标参数
    if (r != null) return unescape(r[2])
    return null //返回参数值
}

7、提供2个数生成区间数组

const rangeArray = (start, end) => Array.apply(null, { length: end - start + 1 }).map((v, i) => i + start)

8、保留小数

const toMoney = (num) => num.toFixed(2).split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(/\,$/, '').split('').reverse().join('')

9、菊花遮罩

const showLoading = (title) => { wx.showLoading({ title: title, mask: true }) }
const hideLoading = () => { wx.hideLoading() }
const showToast = (title, icon = 'none') => { wx.showToast({ title, icon, duration: 1500, mask: true }) }
const hideToast = () => { wx.hideToast() }

10、数字转中文汉字

const toChinesNum = (num) => {
    const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
    const unit = ["", "十", "百", "千", "万"]
    num = parseInt(num)
    let getWan = (temp) => {  
        let strArr = temp.toString().split("").reverse()  
        let newNum = ""  
        for (var i = 0; i < strArr.length; i++) {
            newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum
        } 
        return newNum
    }
    let overWan = Math.floor(num / 10000)
    let noWan = num % 10000
    if (noWan.toString().length < 4) noWan = "0" + noWan
    return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num)
}

 

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