当前位置:   article > 正文

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

小程序公共方法

1、ajax请求

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

 

2、时间格式转换

  1. const formatTime = (date, type) => {
  2. let year = date.getFullYear()//年
  3. let month = date.getMonth() + 1//月
  4. let day = date.getDate()//日
  5. let hour = date.getHours()//时
  6. let minute = date.getMinutes()//分
  7. let second = date.getSeconds()//秒
  8. let getMilliseconds = date.getMilliseconds()//毫秒
  9. if (type == 1) { //2019-12-12 12:12:12
  10.     return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  11. } else if (type == 2) { //2019年12月12日
  12.     if (month < 10) month = '0' + month
  13.     if (day < 10) day = '0' + day
  14.     return year + '年' + month + '月' + day + '日'
  15. } else if (type == 3) { //时间戳 123456789
  16.     return date.getTime()
  17. }
  18. }
  19. const formatNumber = n => {
  20. n = n.toString()
  21. return n[1] ? n : '0' + n
  22. }
  23. 例子:formatTime(new Date(), type)

3、页面跳转

  1. const gotoPage = (url, param) => {
  2. wx.navigateTo({ url: parseUrl(url, param) })
  3. }
  4. 例子:gotoPage(url,{param:param})
  5. const gotoTab = (url, param) => {
  6. wx.reLaunch({ url: parseUrl(url, param) })
  7. }
  8. 例子:gotoTab(url,{param:param})
  9. const backPage = (val) => { //返回堆栈上级页面层数 注:redirectTo页面不会将页面加入堆栈
  10. wx.navigateBack({ delta: val })
  11. }
  12. 例子:backPage(num)//返回几层就输多少
  13. const parseUrl = (url, param) => {
  14. if (typeof(param) !== "object") return url
  15. var str = ''
  16. for (let i in param) {
  17. str += ('&' + i + '=' + param[i])
  18. }
  19. if (url.indexOf('?') > -1) {
  20. return url + str
  21. } else {
  22. return url + '?' + str.substr(1)
  23. }
  24. }

4、排序

  1. const sortFns = (arr, param) => {//数组 排序参数
  2. return arr.sort(compare(param))
  3. }
  4. const compare = (property) => {
  5. return (a, b) => {
  6. var value1 = a[property]
  7. var value2 = b[property]
  8. return value1 - value2
  9. }
  10. }
  11. 例子:sortFns(arr,'param')

5、缓存

  1. const setStorage = (key, data) => { //存
  2. wx.setStorageSync(key, data)
  3. }
  4. const getStorage = (key) => { //取
  5. return wx.getStorageSync(key)
  6. }
  7. const removeStorage = (key) => { //删
  8. wx.removeStorageSync(key)
  9. }

6、url截取参数

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

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、菊花遮罩

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

10、数字转中文汉字

  1. const toChinesNum = (num) => {
  2. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  3. const unit = ["", "十", "百", "千", "万"]
  4. num = parseInt(num)
  5. let getWan = (temp) => {  
  6. let strArr = temp.toString().split("").reverse()  
  7. let newNum = ""  
  8. for (var i = 0; i < strArr.length; i++) {
  9. 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
  10. } 
  11. return newNum
  12. }
  13. let overWan = Math.floor(num / 10000)
  14. let noWan = num % 10000
  15. if (noWan.toString().length < 4) noWan = "0" + noWan
  16. return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num)
  17. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/147989
推荐阅读
相关标签
  

闽ICP备14008679号