小程序util.js常用方法工具类

const moment = require('./moment.min.js'),
const ifRelease = true, //是否是发布版
function getBaseUrl() {
  if (!ifRelease) {
    return "本地调试访问地址 ";
  }
  return "发布后正式地址";
}

//验证对象
let ygCheck = {
  //是否为bool
  parseBool: function(val) {
    if (val == "true" || val == "True" || val == "TRUE" || val == true || val == 1)
      return true;
    else
      return false;
  },
  //是否是合格手机号
  parsePhone: function(val) {
    if (!(/^[1][3,4,5,7,8,9][0-9]{9}$/.test(val)))
      return false;
    else
      return true;
  },
  //是否是数字
  parseNum: function(val) {
    var patrn = /^(-)?\d+(\.\d+)?$/;
    if (patrn.exec(val) == null || val == "")
      return false
    else
      return true
  },
  //是否是 数字和字母
  parseNumAndLetter: function(val) {
    var reg = /^[0-9a-zA-Z]*$/g;
    if (reg.test(val)) {
      return true;
    } else {
      return false;
    }
  },
  //邮箱验证
  parseEmail: function(val) {
    var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
    if (!val) {
      return false;
    }
    if (!reg.test(val)) {
      return false;
    } else {
      return true;
    }
  },
  //身份证验证
  parseIdNumber: function(val) {
    if (!val) {
      return false;
    }
    if (!(/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/.test(val))) {
      return false;
    } else {
      return true;
    }
  },
};
let ygPost = {
  //登录 注册 什么的 需要设置session的地方调用
  postSetSession: function(url, data = {}, success, error) {
    wx.request({
      url: getBaseUrl() + url,
      method: 'post',
      data: data,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        wx.setStorageSync('sessionid', res.header['Set-Cookie']);
        if (success) {
          success(res);
        }
      },
      fail: function(e) {
        if (error) {
          error(e);
        }
      }
    });
  },
  /**
   * 常规调用 需要携带 sessionid 的
   */
  postGetSession: function(url, data = {}, success, error) {
    data.wxOpenId= wx.getStorageSync("openId");
    wx.request({
      url: getBaseUrl() + url,
      method: 'post',
      data: data,
      header: {
        'content-type': 'application/json', // 默认值
        'cookie': wx.getStorageSync("sessionid"),
        'wxOpenId':data.wxOpenId
      },
      success: function(ret) {
        if (ret.data instanceof Object && ret.data.code == "某个具体的code") {
          wx.clearStorage();
          wx.reLaunch({
            url: "登录地址",
            success: function() {
              setTimeout(function() {
                wx.showToast({
                  icon: "none",
                  title: "您的帐号在另一台微信设备登录,您已被迫下线",
                  duration: 3000,
                });
              }, 1000);
            }
          });
          return;
        }
        if (ret.data instanceof Object && ret.data.code == "具体code") {
          wx.reLaunch({
            url: "启动页面地址",
          });
        }else{
          success(ret);
        }
      },
      fail: error
    });
  },
  /**
   * post 没有会话
   */
  postNotSession: function(url, data = {}, success, error) {
    wx.request({
      url: getBaseUrl() + url,
      method: 'post',
      data: data,
      header: {
        'content-type': 'application/json', // 默认值
      },
      success: success,
      fail: error
    });
  },
  /**
   * 上传图片调用
   */
  uploadFile: function(filePaths, success, error,param="") {
    var tempURl="图片上传方法";
    filePaths.forEach(function(url) {
      wx.uploadFile({
        url: getBaseUrl() + tempURl,
        name: 'UploadFile',
        filePath: url,
        formData: {
          content: param,
        },
        header: {
          "Content-Type": "multipart/form-data",
        },
        method: "POST",
        success: function(ret) {
          if (ret.statusCode == 200) {
            let guids = JSON.parse(ret.data).data;
            if (guids.length > 0) {
              success(guids[0]);
            } else {
              success("");
            }
          } else {
            success("");
          }
        },
        fail: function(e) {
          if (error) {
            error(e);
          } else {
            wx.showToast({
              title: '图片上传失败!',
            })
          }
        }
      });
    });
  }
};

//转换对象
let ygSwitch = {
  //将1,234,567.00转换为1234567.00 
  moneyToNumValue: function(val) {
    var num = val.trim();
    var ss = num.toString();
    if (ss.length == 0) {
      return "0";
    }
    return ss.replace(/,/g, "");
  },
  //调用:fmoney("12345.675910", 3),返回12,345.676 
  fmoney: function(s, n) {
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
      r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
  },
  //深复制 引用类型专属
  deepCopy: function(obj) {
    return JSON.parse(JSON.stringify(obj));
  },
  //图片拼接地址
  getImgUrl: function(guid) {
    if (guid) {
      if (guid.indexOf('http') > -1 || guid.indexOf('https') > -1 || guid.indexOf('cn') > -1 || guid.indexOf('com') > -1) {
        return guid;
      } else {
        return `${getBaseUrl()}/Scene/PicShow?picId=${guid}&scopeName=${wx.getStorageSync("scopeName")}`;
      }
    } else {
      return "";
    }
  },
  getErrorImg: function(e, dataSource, that) {
    var errorImgIndex = e.target.dataset.errorindex; //获取循环的下标
    var errorname = e.target.dataset.errorname;
    var imgObject = dataSource + "[" + errorImgIndex + "]." + errorname;
    var errorImg = {}
    errorImg[imgObject] = "../../images/img_default_image_failed.png"
    that.setData(errorImg)
  },
  getErrorImgSingle: function(obj, that) {
    var errorImg = {}
    errorImg[obj] = "../../images/img_default_image_failed.png"
    that.setData(errorImg);
  },
  getImgGuid(imgSrc) {
    var t1 = imgSrc.split("picId=")[1];
    return t1.split("&")[0];
  }
};

//时间类型扩展 方法格式化日期
Date.prototype.ygformat = function(format) {
  var o = {
    "M+": this.getMonth() + 1, //month
    "d+": this.getDate(), //day
    "h+": this.getHours(), //hour
    "m+": this.getMinutes(), //minute
    "s+": this.getSeconds(), //second
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
    "S": this.getMilliseconds() //millisecond
  }
  if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(format))
      format = format.replace(RegExp.$1,
        RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
  return format;
}

//时间帮助对象
let ygDate = {
  //获取当前时间
  getTimeYg: function(format) {
    var newDate = new Date();
    var newDates = new Date(newDate.getTime());
    var d = newDates.ygformat(format);
    return d;
  },
  getTime: function(format) {
    return ygDate.formatDatesServer(new Date(), format);
  },
  //格式化日期
  formatDatesServer: function(date, format) {
    return moment(date).format(format);
  },
  formatDates: function(date, format) {
    var newDate = new Date(date);
    var newDates = new Date(newDate.getTime());
    var d = newDates.ygformat(format);
    return d;
  },
  //格式时间戳
  formatTimestamp: function(date, format) {
    if (format == undefined) {
      format = "yyyy-MM-dd";
    }
    var d = eval('new ' + date.substr(1, date.length - 2));
    return ygDate.formatDates(d, format);
  },
  //日期前一天
  preDate: function(date, format) {
    var newDate = new Date(date);
    var nextDate = new Date(newDate.getTime() - 24 * 60 * 60 * 1000);
    var d = nextDate.ygformat(format);
    return d;
  },
  //日期后一天
  nextDate: function(date, format) {
    var newDate = new Date(date);
    var nextDate = new Date(newDate.getTime() + 24 * 60 * 60 * 1000);
    var d = nextDate.ygformat(format);
    return d;
  },
  //增加天数
  addDay: function(date, days) {
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    var m = d.getMonth() + 1;
    return ygDate.formatDates(d, "yyyy-MM-dd");
  },
  //得到星期数
  getDateWeek: function(date) {
    var today = new Array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
    var newDate = new Date(date);
    return today[newDate.getDay()];
  },
  /**
   * 获取本周开始结束日期
   */
  getWeekRange: function() {
    var today = new Date();
    var nowDayOfWeek = today.getDay(); //当前周的第几天
    if(nowDayOfWeek==0){
      nowDayOfWeek=7;
    }
    var weekStart = new Date();
    weekStart.setDate(today.getDate() - nowDayOfWeek + 1);
    var weekEnd = ygDate.addDay(weekStart, 6);
    var weekRange = {
      weekStart: ygDate.formatDates(weekStart, "yyyy-MM-dd"),
      endWeek: ygDate.formatDates(weekEnd, "yyyy-MM-dd")
    }
    return weekRange;
  },
  getDaysBetween: function (startTime, endTime){
    var startDate = Date.parse(startTime);
    var endDate = Date.parse(endTime);
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    return days;
  }
};

module.exports = {
  ygCheck: ygCheck,
  ygPost: ygPost,
  ygSwitch: ygSwitch,
  ygDate: ygDate,
  ifRelease: ifRelease,
  getBaseUrl: getBaseUrl,
}

具体使用,在头部按需引入,以日期为例

// pages/index/instock.js
const {
  ygCheck,
  ygPost,
  ygSwitch,
  ygDate
} = require("../../../utils/util.js");
const {
  $Message
} = require('../../../dist/base/index.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentDate: ygDate.getTimeYg("yyyy-MM-dd"),
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that=this;
    that.getInStorageInfo();
  },
  getInStorageInfo:function()
  {
    let that = this;
    ygPost.postGetSession("/Test/GetTest", {
		
    }, function (ret) {
      
    }, function () {

    });
  }
})
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值