常用封装方法

[本地数据存、删、查]

/**
 *[本地数据存、删、查]
 * @param  {[type]} key   [description]
 * @param  {[type]} value [description]
 * @return {[type]}       [description]
 */
data: function(key, value) {
    
    
  var getItemValue = function() {
    
    
    var data = localStorage.getItem(key)
    try {
    
    
      data = JSON.parse(data)
    } catch (e) {
    
    
      // data = {};
    }
    return data
  }
  if (key && value === undefined) {
    
    
    return getItemValue()
  } else if (key && value === null) {
    
    
    localStorage.removeItem(key)
  } else {
    
    
    localStorage.setItem(key, JSON.stringify(value))
  }
},

[获取url后参数值]

/**
 * [获取url后参数值]
 * @param  {[type]} param [属性名]
 * @return {[type]}       [属性值]
 * @example
 *        http://xxx.com/a.do?productCode=P001
 *        getParameter('productCode')
 *        result 'P001'
 */
getParameter: function(param) {
    
    
  var reg = new RegExp('[&,?,&]' + param + '=([^\\&]*)', 'i')
  var value = reg.exec(location.search)

  return value ? value[1] : ''
},

[获取URL参数对象]

/**
 *[获取URL参数对象]
 * @param  {[type]} queryString [url]
 * @return {[type]}             [参数值组成的对象]
 */
getQueryMap: function(queryString) {
    
    
  var paramObj = {
    
    }
  var paramList
  var oneQueryMatch
  var regGlobal = /[?&][^?&]+=[^?&#]+/g
  var regOne = /[?&]([^=?]+)=([^?&#]+)/

  queryString = queryString || location.href
  paramList = queryString.match(regGlobal)

  if (!paramList) {
    
    
    return paramObj
  }

  for (var i = 0, len = paramList.length; i < len; i++) {
    
    
    oneQueryMatch = paramList[i].match(regOne)
    if (oneQueryMatch === null) {
    
    
      continue
    }
    paramObj[oneQueryMatch[1]] = oneQueryMatch[2]
  }

  return paramObj
},

金额格式化,20000->20.000,00强制保留2位小数,每隔三位用.隔开

// 金额格式化,20000->20.000,00强制保留2位小数,每隔三位用.隔开
moneyFormatWithDecimal(num) {
    
    
  num = num.toString()
  var num1 = parseFloat(num)
  if (isNaN(num1)) {
    
    
    return false
  }
  if (num.indexOf('.') >= 0) {
    
    
    var lastIndex = num.lastIndexOf('.')
    var num9 =
      num.substring(0, lastIndex) +
      ',' +
      num.substring(lastIndex + 1, num.length)
    const RegExp = /\B(?=(?:\d{3})+(?!\d))/g
    let numformat = num9 && num9.toString().replace(RegExp, '.')
    return numformat
  } else {
    
    
    var num2 = Math.round(num * 100) / 100
    var num3 = num2.toString()
    var num4 = num3.indexOf(',')
    if (num4 < 0) {
    
    
      num4 = num3.length
      num3 += ','
    }
    while (num3.length <= num4 + 2) {
    
    
      num3 += '0'
    }
    const RegExp = /\B(?=(?:\d{3})+(?!\d))/g
    let numformat = num3 && num3.toString().replace(RegExp, '.')
    return numformat
  }
},

金额格式化,20000->20.000

// 金额格式化,20000->20.000
moneyFormat(num) {
    
    
  const RegExp = /\B(?=(?:\d{3})+(?!\d))/g
  // eslint-disable-next-line
  if (num === null || num === undefined || num === 'null' || num === 'undefined' || num === NaN || num === 'NaN') return ''
  num = num.toString()
  if (num.indexOf('.') >= 0) {
    
    
    var lastIndex = num.lastIndexOf('.')
    var betweenDot = num.substring(lastIndex + 1, num.length)
    if (betweenDot && parseInt(betweenDot)) {
    
    
      const beforeDot = num.substring(0, lastIndex)
      const bereeDotFormat = beforeDot && beforeDot.toString().replace(RegExp, '.')
      num =
      bereeDotFormat +
      ',' +
      num.substring(lastIndex + 1, num.length)
      return num
    } else {
    
    
      const tempNum = num.substring(0, lastIndex)
      num = tempNum && tempNum.toString().replace(RegExp, '.')
      return num
    }
  }
  let numformat = num && num.toString().replace(RegExp, '.')
  return numformat
},

金额格式化,1.2%->1,2%

// 金额格式化,1.2%->1,2%
replaceDecimal(num) {
    
    
  let numformat = num && num.toString().replace('.', ',')
  return numformat
},

转换日期格式

/** 转换日期格式
 * @param date : 日期格式|String类型\Integer类型毫秒时间戳 (如:'2012-12-12' | '2012年12月12日' | '20121212' | new Date() | 1574664670000)
 * @param format : String类型 (如: 'yyyy年MM月dd日'或'yyyy年MM月dd日 hh时mm分ss秒',默认'yyyy-MM-dd')
 * @example C.parseDateFormat(new Date(), 'yyyy年MM月dd日') 输出:"2014年04月29日"
 * @example C.parseDateFormat(new Date()) 输出:"2014-04-29"
 * @exmaple C.parseDateFormat("2014-05-07 16:09:47","yyyy年MM月dd日 hh时mm分ss秒")
 *          输出:"2014年05月07日 16时09分47秒"
 **/
parseDateFormat: (date, format) => {
    
    
  if (!date) {
    
    
    return date
  }
  // 排除yyyymmdd格式的入参数据
  if ((typeof date === 'number' || (!isNaN(1 * date) && typeof (1 * date) === 'number')) 
  && String(date).length !== 8) {
    
    
    date = new Date(date * 1)
  }
  if (!isNaN(date) && String(date).length === 8) {
    
    
    date = (date + '').replace(/^(\d{4})(\d{2})(\d{2})$/, '$1/$2/$3')
  }
  var addZero = function(val) {
    
    
    return /^\d{1}$/.test(val) ? '0' + val : val
  }
  format = format || 'yyyy-MM-dd'
  var year = ''
  var month = ''
  var day = ''
  var hours = ''
  var minutes = ''
  var seconds = ''
  if (typeof date === 'string') {
    
    
    var dateReg = /\b(\d{4})\b[^\d]+(\d{1,2})\b[^\d]+(\d{1,2})\b(\s(\d{1,2}):(\d{1,2}):(\d{1,2}))?[^\d]?/
    var dateMatch = date.match(dateReg)
    if (dateMatch) {
    
    
      year = dateMatch[1]
      month = dateMatch[2]
      day = dateMatch[3]
      hours = dateMatch[5]
      minutes = dateMatch[6]
      seconds = dateMatch[7]
    }
  } else {
    
    
    year = date.getFullYear()
    month = date.getMonth() + 1
    day = date.getDate()
    hours = date.getHours()
    minutes = date.getMinutes()
    seconds = date.getSeconds()
  }
  month = addZero(month)
  day = addZero(day)
  hours = addZero(hours)
  minutes = addZero(minutes)
  seconds = addZero(seconds)
  return format.replace('yyyy', year).replace('MM', month).replace('dd', day).replace('hh', hours).replace('mm', minutes).replace('ss', seconds)
},

银行卡格式化

// 银行卡格式化, 6232084755256966655 -> 6232 0847 5525 6966 655
formatBankCard(cardNum) {
    
    
  let bankCardNum = cardNum
    .replace(/\s/g, '')
    .replace(/[^\d]/g, '')
    .replace(/(\d{4})(?=\d)/g, '$1 ')
  return bankCardNum
},

手机号掩码

// 手机号掩码
maskNum(currentNum, start, end) {
    
    
  if (!currentNum) return ''
  return `${
      
      currentNum.substring(0, start)}******${
      
      currentNum.substring(currentNum.length - end)}`
},

isNullOrUndefined

isNullOrUndefined(val) {
    
    
  const toString = Object.prototype.toString
  return toString.call(val) === '[object Undefined]' || toString.call(val) === '[object Null]'
},

计算字符长度,中文2个字符,英文1个字符

// 计算字符长度,中文2个字符,英文1个字符
strlen(str) {
    
    
  var len = 0
  for (var i = 0; i < str.length; i++) {
    
    
    var c = str.charCodeAt(i)
    // 单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (c >= 0xff60 && c <= 0xff9f)) {
    
    
      len++
    } else {
    
    
      len += 2
    }
  }
  return len
},

去除字符串中的所有空格

// 去除字符串中的所有空格
trim(str) {
    
    
  return str.replace(/\s/g, '')
},

英文首字母大写

// 英文首字母大写
replaceFirstUper(str) {
    
    
  str = str.toLowerCase()
  return str.replace(/\b(\w)|\s(\w)/g, function(m) {
    
    
    return m.toUpperCase()
  })
},

防抖

// 防抖
debounce(fn, delay) {
    
    
  var timeout = null// 定义一个定时器
  return function() {
    
    
    if (timeout != null);
    clearTimeout(timeout)// 清除定时器
    timeout = setTimeout(fn, delay)
  }
},

节流

// 节流
function(func, delay) {
    
    
  var timer = null// 定义一个定时器
  var startTime = Date.now()// 设置开始时间
  // console.log(startTime)
  return function() {
    
    
    var curTime = Date.now()
    var remaining = delay - (curTime - startTime) // 剩余时间
    clearTimeout(timer)
    if (remaining <= 0) {
    
     // 第一次出发立即执行
      func.apply(this, arguments)
      startTime = Date.now()
    } else {
    
    
      timer = setTimeout(func, remaining) // 取消当前计时器并重新计算remaining
    }
  }
},

数字动画

// 数字动画
numIncrease: (max, vm, model, time = 2) => {
    
    
  const start = parseInt(vm[model])
  let current = start
  let request = null
  let step = parseInt((max - start) / (60 * time))
  step = step || 1
  const run = () => {
    
    
    current += step
    if (current >= max) {
    
    
      current = max
      cancelAnimationFrame(request)
    } else {
    
    
      request = requestAnimationFrame(run)
    }
    vm[model] = current
  }
  run()
},

时分秒倒计时

/**
 * 时分秒倒计时
 * @params :startTime => 开始时间 '01:50:59'
 * @params :that => this指向
 */
countdown: function(startTime, that) {
    
    
  let maxTime = parseInt(startTime.substr(0, 2)) * 3600 +
    parseInt(startTime.substr(3, 2)) * 60 + parseInt(startTime.substr(6, 2))
  let time = () => {
    
    
    maxTime--
    if (maxTime >= 0) {
    
    
      let hours = Math.floor(maxTime / 3600)
      let minutes = Math.floor(maxTime / 60 - hours * 60)
      let seconds = maxTime - hours * 3600 - minutes * 60
      hours = hours > 9 ? hours : '0' + hours
      minutes = minutes > 9 ? minutes : '0' + minutes
      seconds = seconds > 9 ? seconds : '0' + seconds
      that.rest.vaExpireTime = `${
      
      hours}:${
      
      minutes}:${
      
      seconds}`
    } else {
    
    
      clearInterval(that.timer)
    }
  }
  time()
  that.timer = setInterval(time, 1000)
},

数字序列化

/**
 * 数字序列化,暂时仅支持100以内的数字,100后的数字根据新规则择时调整
 * @param {str\num} '1' '01' 1
 * @param {bool} 格式化后的数据是否需要去除首位0
 * @param {*} endLen
 */
serializeNum(value, needPreZero = false) {
    
    
  if (value === undefined || value === null) {
    
    
    return ''
  }
  value = String(value)
  // 入参补零
  if (value.length < 1) {
    
    
    value = `0${
      
      value}`
  }
  if (new RegExp('(?<!1)(1)$').test(value)) {
    
    
    value = `${
      
      value}st`
  } else if (new RegExp('(?<!1)(2)$').test(value)) {
    
    
    value = `${
      
      value}nd`
  } else if (new RegExp('(?<!1)(3)$').test(value)) {
    
    
    value = `${
      
      value}rd`
  } else {
    
    
    value = `${
      
      value}th`
  }
  if (needPreZero) {
    
    
    return value
  }
  return value.replace(/^0/, '')
},

银行账号、电话进行脱敏处理

// 银行账号、电话进行脱敏处理
desensitization(str, beginLen, endLen) {
    
    
  const len = str.length
  let tempStr, firstStr, lastStr
  if (endLen) {
    
    
    firstStr = str.substr(0, beginLen)
    lastStr = str.substr(endLen)
    const middleStr = str.substring(beginLen, len - Math.abs(endLen)).replace(/[\s\S]/ig, '*')
    tempStr = firstStr + middleStr + lastStr
  } else {
    
    
    lastStr = str.substr(beginLen)
    tempStr = firstStr + lastStr.replace(/[\s\S]/ig, '*')
  }
  if (!beginLen) {
    
    
    firstStr = str.substr(0, beginLen).replace(/[\s\S]/ig, '*')
    tempStr = firstStr + str.substr(beginLen)
  }
  return tempStr
},

地址脱敏

// 地址脱敏
addressDesensitization(str) {
    
    
  if (!str) return ''
  return str.replace(/[0-9]/ig, '*')
},

姓名脱敏

// 姓名脱敏
nameDesensitization(str) {
    
    
  if (!str) return ''
  const firstStr = str.split(' ')[0]
  return `${
      
      firstStr}******`
},

猜你喜欢

转载自blog.csdn.net/weixin_46447120/article/details/129265663