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

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)
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章