uniapp,常用工具函数

  • uniapp,常用工具函数已关闭评论
  • 78 次浏览
  • A+
所属分类:Web前端
摘要

 

/* 处理文件路径 */ export default { //  拨打电话     callPhone(phone) {         uni.makePhoneCall({             phoneNumber: phone //仅为示例         });     },     // 判断对象是否包含空值     /*      ** @return flag      ** @params 目标对象      */     paramsValidate(params) {         let flag = true;         for (var key in params) {             if (params[key] != '0' && !params[key]) {                 return false; // 终止程序             }         }         return flag;     },     // 日期2023-01-03转几小时前,刚刚文字     timeToWords(stringTime) {         if (stringTime) {             // 获取当前             var minute = 1000 * 60;             var hour = minute * 60;             var day = hour * 24;             var week = day * 7;             var month = day * 30;             var time1 = new Date().getTime(); //当前的时间戳             var time2 = Date.parse(new Date(stringTime)); //指定时间的时间戳             var time = time1 - time2;              var result = null;             if (time < 0) {                 result = stringTime             } else if (time / month >= 1) {                 result = parseInt(time / month) + "月前";             } else if (time / week >= 1) {                 result = parseInt(time / week) + "周前";             } else if (time / day >= 1) {                 result = parseInt(time / day) + "天前";             } else if (time / hour >= 1) {                 result = parseInt(time / hour) + "小时前";             } else if (time / minute >= 1) {                 result = parseInt(time / minute) + "分钟前";             } else {                 result = "刚刚";             }             return result;         }     },     // 判断是否是json格式     isJSON(str) {         if (typeof str == "string") {             try {                 var obj = JSON.parse(str)                 if (typeof obj == "object" && obj) {                     return true                 } else {                     return false                 }             } catch (e) {                 return false             }         }     },     // 电话号码加密     phonePas(string, type) {         if (string) {             let str = string.substring(3, 7)             return string.replace(str, '****')         }     },     checkPhone(phone) {         let check = /^(?:(?:+|00)86)?1[3-9]d{9}$/g.test(phone);         return check     },     // 身份证校验     checkIdNumber(idNum) {         let c = /^d{6}(18|19|20)d{2}(0d|10|11|12)([0-2]d|30|31)d{3}[dXx]$/g.test(idNum);         return c     },     // 字符串截取,str,需要截取的字符串,num需要从第几位截取,endStr-结尾的字符串     substr(str, num, endStr) {         return `${str.substring(0,num)}${endStr}`     },     // 判断空对象     isEmpty(obj) {         return Object.keys(obj).length === 0     },     // 年月日转为日期格式     // 日期转换     formatYMD(data, format = '-') {         if (data) {             let time1 = data.split(' ')             let time = time1[0].replace('年', '-').replace('月', '-').replace('日', ' ')             let arr = time.split('-')             let y = arr[0]             let m = arr[1] < 10 ? `0${arr[1]}` : arr[1]             let r = arr[2] < 10 ? `0${arr[2]}` : arr[2]             // 没有秒自动补全秒             if (time1[1].split(':').length < 3) {                 return `${y}${format}${m}${format}${r}${time1[1]?time1[1]+':00':''}`             }             return `${y}${format}${m}${format}${r}${time1[1]?time1[1]:''}`         } else {             return null         }     },     // 日期格式转年月日     formatToYMD(data) {         if (data) {             let time1 = data.split(' ')             let time = time1[0].replace('-', '年').replace('-', '月')             let arr = time1[0].split('-')             let y = arr[0]             let m = arr[1] < 10 ? `${arr[1].split('0')[1]}` : arr[1]             let enr = arr[2]             let r = enr.split('0')[0] ? enr.split('0')[0] : enr.split('0')[1]             return `${y}年${m}月${r}日 ${time1[1]?time1[1]:''}`         } else {             return null         }     },     // 日期格式化     formatDate: function(dateA, format = 'yyyy-MM-dd HH:mm:ss', splitType = "-") {         console.log('dateA', dateA)         const dateB = new Date(dateA).toJSON();         const date = new Date(+new Date(dateB) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(             /.[d]{3}Z/, '')         let arr = date.split(" ")         let dates         switch (format) {             case 'yyyy-MM-dd HH:mm:ss':                 dates = date                 break             case 'yyyy-MM-dd':                 // dates = arr[0]                 dates = arr[0].replace('-', splitType).replace('-', splitType)                 break             case 'HH:mm:ss':                 dates = arr[1]                 break             case 'yyyy-MM-dd HH:mm':                 let arr2 = []                 arr2.push(date.split(":")[0])                 arr2.push(date.split(":")[1])                 dates = arr2.join(":")                 break             case 'MM-dd':                 let newArr = arr[0].split('-')                 let result = []                 if (newArr.length === 3) {                     newArr[1] < 10 ? newArr[1] = newArr[1].split('0')[1] : newArr[1]                     newArr[2] < 10 ? newArr[2] = newArr[2].split('0')[1] : newArr[2]                     result.push(newArr[1])                     result.push(newArr[2])                     dates = result.join(splitType)                 }                 break             case 'HH:mm':                 let newArr2 = arr[1].split(':')                 let arr3 = []                 arr3.push(newArr2[0])                 arr3.push(newArr2[1])                 dates = arr3.join(':')                 break         }         return dates     },     // 获取当前月的最后一天     getLastDay(year, month) {         const isLeapYear = ((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)         const maxDays = [1, 3, 5, 7, 8, 10, 12]         const middleDays = [4, 6, 9, 11]         month = Number(month)         if (month == 2) {             if (isLeapYear) {                 return 29             } else {                 return 28             }         } else if (maxDays.includes(month)) {             return 31         } else if (middleDays.includes(month)) {             return 30         }     },     // 删除对象属性值为空的属性,obj-传入的对象     removeProperty(obj) {         Object.keys(obj).forEach((item) => {             if (obj[item] === '' || obj[item] === undefined || obj[item] === null || obj[item] === 'null') {                 Reflect.deleteProperty(obj,item)             }         })         return obj     },     // base64转path     base64ToPath(base64) {         return new Promise(function(resolve, reject) {             if (typeof window === 'object' && 'document' in window) {                 base64 = base64.split(',')                 var type = base64[0].match(/:(.*?);/)[1]                 var str = atob(base64[1])                 var n = str.length                 var array = new Uint8Array(n)                 while (n--) {                     array[n] = str.charCodeAt(n)                 }                 return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {                     type: type                 })))             }             var extName = base64.match(/data:S+/(S+);/)             if (extName) {                 extName = extName[1]             } else {                 reject(new Error('base64 error'))             }             var fileName = Date.now() + '.' + extName             if (typeof plus === 'object') {                 var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())                 bitmap.loadBase64Data(base64, function() {                     var filePath = '_doc/uniapp_temp/' + fileName                     bitmap.save(filePath, {}, function() {                         bitmap.clear()                         resolve(filePath)                     }, function(error) {                         bitmap.clear()                         reject(error)                     })                 }, function(error) {                     bitmap.clear()                     reject(error)                 })                 return             }             if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {                 var filePath = wx.env.USER_DATA_PATH + '/' + fileName                 wx.getFileSystemManager().writeFile({                     filePath: filePath,                     data: base64.replace(/^data:S+/S+;base64,/, ''),                     encoding: 'base64',                     success: function() {                         resolve(filePath)                     },                     fail: function(error) {                         reject(error)                     }                 })                 return             }             reject(new Error('not support'))         })     }  }  function getLocalFilePath(path) {     if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf(             '_downloads') === 0) {         return path     }     if (path.indexOf('file://') === 0) {         return path     }     if (path.indexOf('/storage/emulated/0/') === 0) {         return path     }     if (path.indexOf('/') === 0) {         var localFilePath = plus.io.convertAbsoluteFileSystem(path)         if (localFilePath !== path) {             return localFilePath         } else {             path = path.substr(1)         }     }     return '_www/' + path }  /* base64转文件路径 */ export function base64ToPath(base64) {     return new Promise(function(resolve, reject) {         if (typeof window === 'object' && 'document' in window) {             base64 = base64.split(',')             var type = base64[0].match(/:(.*?);/)[1]             var str = atob(base64[1])             var n = str.length             var array = new Uint8Array(n)             while (n--) {                 array[n] = str.charCodeAt(n)             }             return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {                 type: type             })))         }         var extName = base64.match(/data:S+/(S+);/)         if (extName) {             extName = extName[1]         } else {             reject(new Error('base64 error'))         }         var fileName = Date.now() + '.' + extName         if (typeof plus === 'object') {             var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())             bitmap.loadBase64Data(base64, function() {                 var filePath = '_doc/uniapp_temp/' + fileName                 bitmap.save(filePath, {}, function() {                     bitmap.clear()                     resolve(filePath)                 }, function(error) {                     bitmap.clear()                     reject(error)                 })             }, function(error) {                 bitmap.clear()                 reject(error)             })             return         }         if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {             var filePath = wx.env.USER_DATA_PATH + '/' + fileName             wx.getFileSystemManager().writeFile({                 filePath: filePath,                 data: base64.replace(/^data:S+/S+;base64,/, ''),                 encoding: 'base64',                 success: function() {                     resolve(filePath)                 },                 fail: function(error) {                     reject(error)                 }             })             return         }         reject(new Error('not support'))     }) }