vue-公共方法

目的:

这篇文章主要是记录一下平时在项目中都会用到的一些通用方法,可以放在项目的utils文件下,使用起来比较方便。

  • 日期对象转为日期字符串

  • /**
     * 日期对象转为日期字符串
     * @param date 需要格式化的日期对象
     * @param sFormat 输出格式,默认为yyyy-MM-dd                         年:y,月:M,日:d,时:h,分:m,秒:s
     * @example  dateFormat(new Date())                                "2017-02-28"
     * @example  dateFormat(new Date(),'yyyy-MM-dd')                   "2017-02-28"
     * @example  dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss')         "2017-02-28 09:24:00"
     * @example  dateFormat(new Date(),'hh:mm')                       "09:24"
     * @example  dateFormat(new Date(),'yyyy-MM-ddThh:mm:ss+08:00')   "2017-02-28T09:24:00+08:00"
     * @returns {boolean}
     */
    function dateFormat(date, sFormat) {
        if (isEmpty(sFormat)) {
            sFormat = 'yyyy-MM-dd'
        }
    
        if (!(date instanceof Date)) {
            try {
                if (isEmpty(date)) {
                    return ''
                }
                if (date.lastIndexOf('.') !== -1) {
                    date = date.substr(0, date.lastIndexOf('.'))
                }
                date = date.replace(/\-/g, '/') // eslint-disable-line
                date = new Date(date)
            } catch (e) {
                console.log(e)
            }
        }
    
        let time = {
            Year: 0,
            TYear: '0',
            Month: 0,
            TMonth: '0',
            Day: 0,
            TDay: '0',
            Hour: 0,
            THour: '0',
            hour: 0,
            Thour: '0',
            Minute: 0,
            TMinute: '0',
            Second: 0,
            TSecond: '0',
            Millisecond: 0,
        }
        time.Year = date.getFullYear()
        time.TYear = String(time.Year).substr(2)
        time.Month = date.getMonth() + 1
        time.TMonth = time.Month < 10 ? '0' + time.Month : String(time.Month)
    
        time.Day = date.getDate()
        time.TDay = time.Day < 10 ? '0' + time.Day : String(time.Day)
    
        time.Hour = date.getHours()
        time.THour = time.Hour < 10 ? '0' + time.Hour : String(time.Hour)
        time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12
        time.Thour = time.hour < 10 ? '0' + time.hour : String(time.hour)
    
        time.Minute = date.getMinutes()
        time.TMinute = time.Minute < 10 ? '0' + time.Minute : String(time.Minute)
        time.Second = date.getSeconds()
        time.TSecond = time.Second < 10 ? '0' + time.Second : String(time.Second)
        time.Millisecond = date.getMilliseconds()
    
        return sFormat.replace(/yyyy/ig, String(time.Year))
        .replace(/yyy/ig, String(time.Year))
        .replace(/yy/ig, time.TYear)
        .replace(/y/ig, time.TYear)
    
        .replace(/MM/g, time.TMonth)
        .replace(/M/g, String(time.Month))
    
        .replace(/dd/ig, time.TDay)
        .replace(/d/ig, String(time.Day))
    
        .replace(/HH/g, time.THour)
        .replace(/H/g, String(time.Hour))
        .replace(/hh/g, time.Thour)
        .replace(/h/g, String(time.hour))
    
        .replace(/mm/g, time.TMinute)
        .replace(/m/g, String(time.Minute))
        .replace(/ss/ig, time.TSecond)
        .replace(/s/ig, String(time.Second))
        .replace(/fff/ig, String(time.Millisecond))
    }
    
  • 字符串转成时间

  • /**
     * 字符串转成时间
     * @param v
     * @return {Object}
     */
    const stingToTime = (v) => {
      if(!isEmpty(v)){
        return {
          year: v.slice(0, 4),
          month: v.slice(4, 6),
          day: v.slice(6, 8),
          hour: v.slice(8, 10),
          minute: v.slice(10, 12),
          second: v.slice(12,14),
        }
      }
    }
    
  • 判断对象为空

  • /**
     * 判断对象为空
     * @param v
     * @return {boolean}
     */
    const isEmpty = (v) => {
        if (typeof v === 'undefined') {
            return true
        }
        if (v === undefined || v === 'undefined') {
            return true
        }
        if (v === null) {
            return true
        }
        if (v === '' || v === 'null') {
            return true
        }
        if (v === 0) {
            return true
        }
        switch (typeof v) {
            case 'string' :
                if (v.trim().length === 0) {
                    return true
                }
                break
            case 'boolean' :
                if (!v) {
                    return true
                }
                break
            case 'number' :
                if (v === 0) {
                    return true
                }
                break
            case 'object' :
                return undefined !== v.length && v.length === 0
        }
        return false
    }
    
  • 判断手机号码是否正确

  • /**
     * 手机号码是否正确
     * @param number 手机号码
     * @return Boolean
     * */
    const isMobileNumber = (number) => {
        return /^(13[0-9]|14[579]|15[012356789]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(number)
    }
    
  • 生成唯一id

    /**
     * 生成唯一的id
     * @param len 长度
     * @param radix 基数
     * */
    const uuid = (len, radix) => {
      let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
      let uuid = [], i;
      radix = radix || chars.length;
    
      if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
      } else {
        // rfc4122, version 4 form
        let r;
    
        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
    
        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random()*16;
            uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
          }
        }
      }
    
      return uuid.join('');
    }
    
  • 正则匹配数字

  • /**
     * 正则匹配数字
     * @param value 要匹配的值
     * @param type 保留的小数点位数,最多四位
     * */
    const matchInputByRegular = (value, type = 2) => {
      if(type === 0) {
        return value.replace(/[^\d]/g, '');
      }
      if(type === 2) {
        return value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1');
      }
      if(type === 3) {
        return value.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1');
      }
      if(type === 4 ) {
        return value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, '$1');
      }
    }
    
  • 小数自动取两位,不足补全

  • /**
     * 小数自动取两位,不足自动补全
     * @param value 要匹配的值
     * */
    const changeTwoDecimal = (x) => {
        let fx = parseFloat(x);
        if (isNaN(fx)) {
            alert('function:changeTwoDecimal->parameter error');
            return false;
        }
        fx = Math.round(x * 100) / 100;
        let sx = fx.toString();
        let posdecimal = sx.indexOf('.');
        if (posdecimal < 0) {
            posdecimal = sx.length;
            sx += '.';
        }
        while (sx.length <= posdecimal + 2) {
            sx += '0';
        }
        return sx;
    }
    
  • 乘法运算,避免数据相乘小数点后产生多位数和计算精度损失

  • /**
     * 乘法运算,避免数据相乘小数点后产生多位数和计算精度损失。
     *
     * @param num1被乘数 | num2乘数
     */
    const bcmul = (num1, num2,s) => {
        let baseNum = 0,ret;
        try {
            if (num1.indexOf(".") !== -1){
                baseNum += num1.split(".")[1].length;
            } else {
                baseNum += 0;
            }
    
        } catch (e) {
            console.log(e)
        }
        try {
            if (num2.indexOf(".") !== -1){
                baseNum += num2.split(".")[1].length;
            } else {
                baseNum += 0;
            }
    
        } catch (e) {
            console.log(e)
        }
        ret=Number(num1.replace(".", "")) * Number(num2.replace(".", "")) / Math.pow(10, baseNum);
        return bcFixed(ret,s);
    }
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容