import config from './config.js' function msg(title = '', param={}){ if(!title){ return; } const duration = param.duration || 1500; const mask = param.mask || false; const icon = param.icon || 'none'; let options = { title, duration, mask, icon } if(param.type){ // options.image = '/static/' + param.type + '.png'; } uni.showToast(options); } function date(format, timeStamp){ let date = new Date(timeStamp * 1000), Y = date.getFullYear(), m = date.getMonth() + 1, d = date.getDate(), H = date.getHours(), i = date.getMinutes(), s = date.getSeconds(); m = m < 10 ? '0' + m : m; d = d < 10 ? '0' + d : d; H = H < 10 ? '0' + H : H; i = i < 10 ? '0' + i : i; s = s < 10 ? '0' + s : s; return format.replace(/[YmdHis]/g, key=>{ return {Y,m,d,H,i,s}[key]; }); } /** * 节流原理:在一定时间内,只能触发一次 * * @param {Function} func 要执行的回调函数 * @param {Number} wait 延时的时间 * @param {Boolean} immediate 是否立即执行 * @return null * this.throttle(this.getResult, this.timeout, this.immediate); * $tools.throttle(submit) */ let timer, flag; function throttle(func, wait = 2000, immediate = true) { if (immediate) { if (!flag) { flag = true; // 如果是立即执行,则在wait毫秒内开始时执行 typeof func === 'function' && func(); timer = setTimeout(() => { flag = false; }, wait); } } else { if (!flag) { flag = true // 如果是非立即执行,则在wait毫秒内的结束处执行 timer = setTimeout(() => { flag = false typeof func === 'function' && func(); }, wait); } } } /** * 防抖原理:一定时间内,只有最后一次操作,再过wait毫秒后才执行函数 * * @param {Function} func 要执行的回调函数 * @param {Number} wait 延时的时间 * @param {Boolean} immediate 是否立即执行 * @return null * this.debounce(this.getResult, this.timeout, this.immediate); */ let timeout = null; function debounce(func, wait = 500, immediate = false) { // 清除定时器 if (timeout !== null) clearTimeout(timeout); // 立即执行,此类情况一般用不到 if (immediate) { var callNow = !timeout; timeout = setTimeout(function() { timeout = null; }, wait); if (callNow) typeof func === 'function' && func(); } else { // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法 timeout = setTimeout(function() { typeof func === 'function' && func(); }, wait); } } function inAction(fn, that, timeout = 2000){ if(that['in' + fn]){ return true } that['in' + fn] = true; setTimeout(()=>{ that['in' + fn] = false; }, timeout) return false; } function match(str, type, showMsg=true){ let exp = ''; switch(type){ case 'mobile': if(str === ''){ showMsg && msg('请填写手机号码'); return false; } exp = /(^1[3|4|5|6|7|8|9][0-9]{9}$)/; //手机号 if(!exp.test(str)){ showMsg && msg('手机号码格式不正确'); return false; } break; case 'pwd': if(str === ''){ showMsg && msg('请填写密码'); return false; } //必须加break; 否则pwd校验正确后会进入 case 'code' break; case 'code': if(str === ''){ showMsg && msg('请填写验证码'); return false; } if(!/^[0-9]+$/.test(str)){ showMsg && msg('验证码不正确'); return false; } break; case 'idcard': if(str === ''){ showMsg && msg('请填写身份证号码'); return false; } if(!/^(\d{17}[\d|x|X]|\d{15})$/.test(str)){ showMsg && msg('请输入正确身份证号'); return false; } break; } return true; } // 返回上一页 const prePage = (num=1) => { let pages = getCurrentPages(); let prePage = pages[pages.length -1- num]; // console.log('prePage--',prePage); // #ifdef H5 return prePage; // #endif return prePage.$vm; } // 上传图片--注按需要对res处理 JSON.parse() function uploadImg(formData){ return new Promise((resolve,reject)=>{ uni.chooseImage({ count:1, success(chooseImageRes){ // resolve(chooseImageRes.tempFilePaths[0]); const tempFilePaths = chooseImageRes.tempFilePaths[0]; // const token = sessionStorage.getItem('token'); const token = uni.getStorageSync('token'); uni.showLoading({ title: '请稍后..', mask: true, }) uni.uploadFile({ url:config.uploadImgUrl, filePath: tempFilePaths, name: 'file', formData:formData, header: { 'token':token, }, success:(res)=>{ //需要JSON.parse let data = JSON.parse(res.data); if(!data || data.code !== 1 ){ msg('上传失败'); reject(); return; } // console.log('tools uploadImg---',data); //即为全路径地址 let fullurl = data.data.fullurl; resolve(fullurl); }, fail:(err)=>{ console.log('err--',err); msg('上传失败'); reject(); }, complete:()=> { uni.hideLoading(); }, }) }, fail(err){ // msg('打开相册失败'); reject(err) } }) }) } function uploadVideo(formData={}){ return new Promise((resolve,reject)=>{ uni.chooseVideo({ sourceType: ['camera', 'album'], success(chooseVideoRes){ // resolve(chooseVideoRes.tempFilePaths[0]); const tempFilePath = chooseVideoRes.tempFilePath; // const token = sessionStorage.getItem('token'); const token = uni.getStorageSync('token'); uni.showLoading({ title: '请稍后..', mask: true, }) formData.act='video'; uni.uploadFile({ url:config.uploadVideoUrl, filePath: tempFilePath, name: 'file', formData:formData, header: { 'token':token, }, success:(res)=>{ //需要JSON.parse let data = JSON.parse(res.data); if(!data || data.code !== 1 ){ msg('上传失败'); reject(); return; } // //即为全路径地址 resolve(data.data.fullurl); // console.log('res---',res); }, fail:(err)=>{ console.log('err--',err); msg('上传失败'); reject(); }, complete:()=> { uni.hideLoading(); }, }) }, fail(err){ // msg('打开相册失败'); reject(err) } }) }) } // 查看单张图片 function previewImg(urls,idx=0){ uni.previewImage({ current: urls[idx], urls: urls, indicator: "number" }) } //单个授权,针对定位await api.checkDeviceAuthorize('scope.userLocation','请开启定位,方便司机到达您的位置'); let hasOpenDeviceAuthorizeModal = false; function checkDeviceAuthorize(scope,tipText) { if (hasOpenDeviceAuthorizeModal) { return } hasOpenDeviceAuthorizeModal = true return new Promise((resolve, reject) => { uni.getSetting().then((result) => { // this.authorizeCamera = result.authSetting['scope.camera'] // console.log('getSetting 查看所有授权',result); let authSetting = result[1]['authSetting']; if (authSetting[scope]) { // console.log('getSetting 已授权',result); // 授权成功 resolve({hasScoped:true}) hasOpenDeviceAuthorizeModal = false } else { // 没有授权,弹出授权窗口 // 注意: wx.authorize 只有首次调用会弹框,之后调用只返回结果,如果没有授权需要自行弹框提示处理 // console.log('getSetting 查询没有授权,uni.authorize发起授权') uni.authorize({ scope: scope, success: (res) => { // console.log('authorize ok', res) resolve({initAuth:true}) hasOpenDeviceAuthorizeModal = false }, fail: (err) => { // console.log('authorize err 弹层提示', err) openConfirm(scope,tipText,(isTrue)=>{ if(isTrue){ // resolve({popAuth:true}) reject(new Error('popAuth:true but onShow ok')); //onShow会得新调用 hasOpenDeviceAuthorizeModal = false }else{ reject(new Error('authorize fail')) hasOpenDeviceAuthorizeModal = false } }) } }) } }) }) }; function openConfirm(scope,tipText,callback) { return uni.showModal({ content: tipText, confirmText: '确认', cancelText: '取消', success: (res) => { // 点击“确认”时打开设置页面 if (res.confirm) { // console.log('用户点击确认') uni.openSetting({ success: (res) => { // console.log("wx.openSetting success res..",res) if(typeof callback == 'function' && res.authSetting[scope]==true){ callback(true); } }, fail:()=>{ callback(false) } }) } else { // console.log('用户点击取消') callback(false) } }, }) }; ///**详情页处理富文本 details仅是变化替换部分a.replace(/(abc)<\/text>/,function(match,$1) $1=abc---------------------------------------------------------------------- */ const replaceDetail = (details = '') => { //newContent仅是details替换后内容; let newContent = details.replace(/]*>/gi, function (match, capture) { //去除三标签 match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, ''); match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, ''); match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, ''); return match; }); newContent = newContent.replace(/]*\/>/gi, ''); newContent = newContent.replace(/{ return String(num).length < 2 ? '0' + num : num; } const handleDate=(date)=>{ let m = handleStrLength(date.getMonth() + 1); let d = handleStrLength(date.getDate()); // let h = handleStrLength(date.getHours()); // let mm = handleStrLength(date.getMinutes()); // let dateStr = date.getFullYear() + "-" + m + "-" + d + " " + h + ":" + mm; let dateStr = date.getFullYear() + "-" + m + "-" + d; return dateStr; } const handleDateTime=(date)=>{ let m = handleStrLength(date.getMonth() + 1); let d = handleStrLength(date.getDate()); let h = handleStrLength(date.getHours()); let mm = handleStrLength(date.getMinutes()); let dateStr = date.getFullYear() + "-" + m + "-" + d + " " + h + ":" + mm; // let dateStr = date.getFullYear() + "-" + m + "-" + d; return dateStr; } export default { msg, date, throttle, debounce, inAction, prePage, uploadImg, uploadVideo, previewImg, checkDeviceAuthorize, replaceDetail, handleDate, handleDateTime, match }