/** * @param {*} date * @returns 2019/08/10 12:12:12 */ export const formatTime = date => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') } const formatNumber = n => { n = n.toString() return n[1] ? n : '0' + n } /** * 版本号比较 * https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html */ export const compareVersion = function (v1, v2) { v1 = v1.split('.') v2 = v2.split('.') const len = Math.max(v1.length, v2.length) while (v1.length < len) { v1.push('0') } while (v2.length < len) { v2.push('0') } for (let i = 0; i < len; i++) { const num1 = parseInt(v1[i]) const num2 = parseInt(v2[i]) if (num1 > num2) { return 1 } else if (num1 < num2) { return -1 } } return 0 } // 由于wx.getStorageSync有一定概率取不到值,若取不到再取一次 export const getStorageSync = key => { try { let value = wx.getStorageSync(key) if (!value) { value = wx.getStorageSync(key) } return value || '' } catch (e) { return '' } } export const setStorageSync = (key, value) => { if (key) { try { wx.setStorageSync(key, isUndef(value) ? '' : value) } catch (e) { // Do something when catch error } } } export const removeStorageSync = key => { if (key) { try { wx.removeStorageSync(key) } catch (e) { // Do something when catch error } } } export const clearStorageSync = () => { try { wx.clearStorageSync() } catch (e) { // Do something when catch error } } // 获取用户登录信息 export const getLoginUserInfo = () => { return getStorageSync('USERINFO') } export const showToast = obj => { /*wx.showToast*/ if (!obj || !obj.title) { return console.warn('title is required!') } try { obj.icon = obj.icon || 'none' obj.duration = obj.duration || 3000 obj.mask = obj.mask || false wx.showToast(obj) } catch (e) { // Do something when catch error } } export const showModal = obj => { if (!obj || !obj.content) { return console.warn('content is required!') } try { wx.showModal({ title: obj.title || '', content: obj.content || '', showCancel: obj.showCancel ? true : false, cancelText: obj.cancelText || '取消', confirmText: obj.confirmText || '确定', success: function (res) { if (obj.success) obj.success(res) } }) } catch (e) { // Do something when catch error } } export const showLoading = obj => { if (!obj || !obj.title) { return console.warn('title is required!') } try { wx.showLoading({ title: obj.title, mask: obj.mask || false, success: function (res) { if (obj.success) obj.success(res) } }) } catch (e) { // Do something when catch error } } export const hideLoading = obj => { try { wx.hideLoading({ success: function (res) { if (obj && obj.success) obj.success(res) } }) } catch (e) { // Do something when catch error } } export const showActionSheet = function (obj) { try { wx.showActionSheet({ itemList: obj.itemList, itemColor: obj.itemColor || '#000', success(res) { if (obj.success) obj.success(res.tapIndex) }, fail(res) { if (obj.fail) obj.fail(res) } }) } catch (e) { // Do something when catch error } } export const chooseImage = function (obj) { if (!obj) return try { wx.chooseImage({ count: obj.count || 1, sizeType: obj.sizeType || ['original', 'compressed'], sourceType: obj.sourceType || ['album', 'camera'], success(res) { // tempFilePath可以作为img标签的src属性显示图片 const tempFilePaths = res.tempFilePaths if (obj.success) obj.success(tempFilePaths) } }) } catch (e) { // Do something when catch error } } export const reLaunch = function (path) { try { wx.reLaunch({ url: path }) } catch (e) { // Do something when catch error } } export const redirectTo = function (path) { try { wx.redirectTo({ url: path }) } catch (e) { // Do something when catch error } } export const navigateTo = function (path) { try { wx.navigateTo({ url: path }) } catch (e) { // Do something when catch error } } export const navigateBack = function (delta) { try { wx.navigateBack({ delta: delta || 1 }) } catch (e) { // Do something when catch error } } export const promisify = fun => { /* function使用转成Promise形式 */ return (options, ...params) => { return new Promise((resolve, reject) => { const extras = { success: resolve, fail: reject } fun({ ...options, ...extras }, ...params ) }) } } export const filterEmoji = str => { /*过滤表情*/ if (str) { return str.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, '') } return '' } export const isUndef = val => { return val === undefined || val === null } export const isDef = val => { return val !== undefined && val !== null } export const deepClone = obj => { /*深度克隆对象*/ if (null === obj || 'object' !== typeof obj) { return obj } let clone if (obj instanceof Date) { clone = new Date() clone.setTime(obj.getTime()) return clone } if (obj instanceof Array) { clone = [] let i, n = obj.length for (i = 0; i < n; i++) { clone[i] = util.deepClone(obj[i]) } return clone } if (obj instanceof Object) { clone = {} for (let key in obj) { if (obj.hasOwnProperty(key)) { clone[key] = util.deepClone(obj[key]) } } return clone } throw new Error(`Unable to clone obj! Its type isn't supported.`) } export const money = (m, c, w) => { /*m:金额c:保留小数位数,只能取值0,1,2w:1返回整个金额,2返回整数部分,3返回小数部分*/ if (c !== 0 && c !== 1 && c !== 2) { console.log('传入保留小数位数参数错误') return '' } if (w !== 1 && w !== 2 && w !== 3) { console.log('传入返回类型参数错误') return '' } if (0 === m) { /*由于0=false,需特殊处理*/ return deal('0', '') } else { if (!m || isNaN(m)) { return '' } m = m.toString() if (-1 === m.indexOf('.')) { return deal(m, '') } else { var s_arr = m.split('.') return deal(s_arr[0], s_arr[1]) } } function deal(p, f) { /*p为整数部分*/ if (0 === c) { if (1 === w) { return p } else if (2 === w) { return p } else if (3 === w) { return '' } } else if (1 === c) { if (0 === f.length) { f = '0' } else if (f.length >= 2) { f = f.substring(0, 1) } if (1 === w) { return p + '.' + f } else if (2 === w) { return p } else if (3 === w) { return f } } else if (2 === c) { if (0 === f.length) { f = '00' } else if (1 === f.length) { f = f + '0' } else if (f.length >= 3) { f = f.substring(0, 2) } if (1 === w) { return p + '.' + f } else if (2 === w) { return p } else if (3 === w) { return f } } } } // ahex 转 rgba export const colorToRgba = (color) => { let rgba = '' color = color.substr(1) let colorLen = color.length let aValue, rValue, gValue, bValue aValue = '0xFF' if (colorLen === 6 || colorLen === 8) { if (colorLen === 8) { aValue = '0x' + color.substr(0, 2) color = color.substr(2) } rValue = '0x' + color.substr(0, 2) gValue = '0x' + color.substr(2, 2) bValue = '0x' + color.substr(4, 2) let alpha = parseInt(aValue) / 255.0 if (JSON.stringify(alpha).length > 4) { //小数点超过三位,四舍五入小数点后两位 alpha = alpha.toFixed(2) } rgba = 'rgba(' + parseInt(rValue) + ',' + parseInt(gValue) + ',' + parseInt(bValue) + ',' + alpha + ')' } return rgba } export const dateToTimestamp = (date) => { // 可以这样做 var timestamp = new Date(date.replace(/-/g, '/')).valueOf() return timestamp } export const timestampToDate = (timestamp) => { let date = new Date(timestamp * 1000) const Y = date.getFullYear() + '-' const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-' const D = date.getDate() return Y + M + D } // 脱敏处理,str脱敏字符串,左边保留字数,右边保留字数,替换字符串* export const desensitization = (str, begin, end, char) => { let len = str.length const c = char || '*' if (len > 1) { if (len <= begin) { let leftStr = str.substring(0, 1) let s = '' try { for (let i = 1; i < len; i++) { s = s + c } } catch (error) { return str } s = leftStr + s return s } else if (len <= end) { let leftStr = str.substring(0, begin) let rightStr = str.substring(len - 1, len) let s = '' try { for (let i = 0; i < len - begin; i++) { s = s + c } } catch (error) { return str } s = leftStr + s + rightStr return s } else { var leftStr = str.substring(0, begin) var rightStr = str.substring(len - end, len) let s = '' try { for (let i = 0; i < len - end - begin; i++) { s = s + c } } catch (error) { return str } s = leftStr + s + rightStr return s } } else { return str } } /** * 表单验证 */ export const validator = { /*校验字段合法性rule*/ checkMobile: s => { /*校验手机号格式是否正确*/ if (s) { var rule = /^\d{3,20}$/ return rule.test(s) } return false }, checkEmail: s => { /*校验邮箱格式是否正确*/ if (s) { var rule = /^(([^<>()\[\]\\.,:\s@"]+(\.[^<>()\[\]\\.,:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return rule.test(s) } return false }, checkPwd: s => { /*校验登录密码格式是否正确*/ if (s) { var rule = /^(?=.*[a-zA-Z]+)(?=.*[0-9]+)[a-zA-Z0-9]{8,16}$/ return rule.test(s) } return false }, checkCode: s => { /*校验短信或邮箱验证码格式是否正确*/ if (s) { var rule = /^\d{6}$/ return rule.test(s) } return false }, checkImgCode: s => { /*校验图片验证码格式是否正确*/ if (s) { var rule = /^[a-zA-Z]{4}$/ return rule.test(s) } return false }, checkNickname: s => { /*校验昵称格式是否正确*/ if (s) { var rule = /^[A-Za-z0-9\u4e00-\u9fa5]{2,20}$/ return rule.test(s) } return false } }