123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414 |
- 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(/<text>(abc)<\/text>/,function(match,$1) $1=abc---------------------------------------------------------------------- */
- const replaceDetail = (details = '') => {
- //newContent仅是details替换后内容;
- let newContent = details.replace(/<img[^>]*>/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(/<br[^>]*\/>/gi, '');
- newContent = newContent.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0 auto;"');
- return newContent;
- }
- //处理选择时间
- const handleStrLength=(num)=>{
- 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
- }
|