常用的工具函数

得到两个数组的并集, 两个数组的元素为数值或字符串
//tools.js
export const getUnion = (arr1, arr2) => {
  return Array.from(new Set([...arr1, ...arr2]))
}

//调用页面
import { getUnion } from '@/libs/tools'

this.getUnion  = getUnion([1,2,3,5],[1,4,6]) 
//(6) [1, 2, 3, 5, 4, 6]

// 示例 

this.openedNames = getUnion(this.openedNames, this.getOpenedNamesByActiveName(name)) 

// 回调函数
getOpenedNamesByActiveName (name) { 
   return this.$route.matched.map(item => item.name).filter(item => item !== name) 
}

  

/**
* @param {Array} target 目标数组
* @param {Array} arr 需要查询的数组
* @description 判断要查询的数组是否至少有一个元素包含在目标数组中
*/

//tools.js
export const hasOneOf = (targetarr, arr) => {
    return targetarr.some(_ => arr.indexOf(_) > -1)
  }
   
   
  //utils.js
  import { hasOneOf} from '@/libs/tools'
   
  this.hasOneOf  = hasOneOf(['super_admin', 'admin'],['admin'])  //true
  this.hasOneOf  = hasOneOf(['super_admin', 'admin'],['徐文龙'])  //false
   
  //高级调用
  export const showByAccess = (access, canViewAccess) => {
    return hasOneOf(canViewAccess, access)
  }



/**
* @param {String|Number} timeStamp 时间戳
* @returns {String} 相对时间字符串
*/
  export const getRelativeTime = timeStamp => {
    // 判断当前传入的时间戳是秒格式还是毫秒
    const IS_MILLISECOND = isMillisecond(timeStamp)
    // 如果是毫秒格式则转为秒格式
    if (IS_MILLISECOND) Math.floor(timeStamp /= 1000)
    // 传入的时间戳可以是数值或字符串类型,这里统一转为数值类型
    timeStamp = Number(timeStamp)
    // 获取当前时间时间戳
    const currentTime = Math.floor(Date.parse(new Date()) / 1000)
    // 判断传入时间戳是否早于当前时间戳
    const IS_EARLY = isEarly(timeStamp, currentTime)
    // 获取两个时间戳差值
    let diff = currentTime - timeStamp
    // 如果IS_EARLY为false则差值取反
    if (!IS_EARLY) diff = -diff
    let resStr = ''
    const dirStr = IS_EARLY ? '前' : '后'
    // 少于等于59秒
    if (diff <= 59) resStr = diff + '秒' + dirStr
    // 多于59秒,少于等于59分钟59秒
    else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr
    // 多于59分钟59秒,少于等于23小时59分钟59秒
    else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr
    // 多于23小时59分钟59秒,少于等于29天59分钟59秒
    else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr
    // 多于29天59分钟59秒,少于364天23小时59分钟59秒,且传入的时间戳早于当前
    else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp)
    else resStr = getDate(timeStamp, 'year')
    return resStr
  }


this.getRelativeTime =  getRelativeTime(1562860952)
//"43秒前"
this.getRelativeTime =  getRelativeTime(1560268952)
//"30天前"



/**
* @param {Number} timeStamp 判断时间戳格式是否是毫秒
* @returns {Boolean}
*/
const isMillisecond = timeStamp => {
    const timeStr = String(timeStamp)
    return timeStr.length > 10
  }



  /**
* @param {Number} timeStamp 传入的时间戳
* @param {Number} currentTime 当前时间时间戳
* @returns {Boolean} 传入的时间戳是否早于当前时间戳
*/
  const isEarly = (timeStamp, currentTime) => {
    return timeStamp < currentTime
  }



  /**
* @param {Number} num 数值
* @returns {String} 处理后的字符串
* @description 如果传入的数值小于10,即位数只有1位,则在前面补充0
*/
  const getHandledValue = num => {
    return num < 10 ? '0' + num : num
  }
  
  let getHandled =  getHandledValue(8);
//   console.log(getHandled);//08



/**
* @param {Number} timeStamp 传入的时间戳
* @param {Number} startType 要返回的时间字符串的格式类型,传入'year'则返回年开头的完整时间
*/
const getDate = (timeStamp, startType) => {
    const d = new Date(timeStamp * 1000)
    const year = d.getFullYear()
    const month = getHandledValue(d.getMonth() + 1)
    const date = getHandledValue(d.getDate())
    const hours = getHandledValue(d.getHours())
    const minutes = getHandledValue(d.getMinutes())
    const second = getHandledValue(d.getSeconds())
    let resStr = ''
    if (startType === 'year') resStr = year + '-' + month + '-' + date + ' '
       + hours + ':' + minutes + ':' + second
    else resStr = month + '-' + date + ' ' + hours + ':' + minutes
    return resStr
  }

this.getDate =getDate(1554998912)
//"04-12 00:08"
this.getDate =getDate(1554998912,'year')
//"2019-04-12 00:08:32"



/**
* @param {String|Number} value 要验证的字符串或数值
* @param {*} validList 用来验证的列表
*/
export function oneOf(value, validList) {
    for (let i = 0; i < validList.length; i++) {
      if (value === validList[i]) {
        return true
      }
    }
    return false
  }

this.oneOf = oneOf('js', ['html', 'text']) //false
this.oneOf = oneOf('text', ['html', 'text']) //true



/**
* 绑定的值的类型, enum: ['html', 'text']
*/
valueType: {
    type: String,
    default: 'html',
    validator: (val) => {
      return oneOf(val, ['html', 'text'])
    }
  }



  /**
* @returns {String} 当前浏览器名称
*/
  export const getExplorer = () => {
    const ua = window.navigator.userAgent
    const isExplorer = (exp) => {
      return ua.indexOf(exp) > -1
    }
    if (isExplorer('MSIE')) return 'IE'
    else if (isExplorer('Firefox')) return 'Firefox'
    else if (isExplorer('Chrome')) return 'Chrome'
    else if (isExplorer('Opera')) return 'Opera'
    else if (isExplorer('Safari')) return 'Safari'
  }
  
  this.getExplorer = getExplorer() 
//"Chrome"



/**
* @description 绑定事件 on(element, event, handler)
*/
export const on = (function () {
    if (document.addEventListener) {
      return function (element, event, handler) {
        if (element && event && handler) {
          element.addEventListener(event, handler, false)
        }
      }
    } else {
      return function (element, event, handler) {
        if (element && event && handler) {
          element.attachEvent('on' + event, handler)
        }
      }
    }
  })()
  


  /**
* @description 解绑事件 off(element, event, handler)
*/
  export const off = (function () {
    if (document.removeEventListener) {
      return function (element, event, handler) {
        if (element && event) {
          element.removeEventListener(event, handler, false)
        }
      }
    } else {
      return function (element, event, handler) {
        if (element && event) {
          element.detachEvent('on' + event, handler)
        }
      }
    }
  })()


  import { on, off } from '@/libs/tools'

  @contextmenu="handleDocumentContextmenu"
    mounted () {
    on(document, 'contextmenu', this.handleDocumentContextmenu)
    },
    beforeDestroy () {
    off(document, 'contextmenu', this.handleDocumentContextmenu)
    }
    handleDocumentContextmenu () {
        this.canMove = false
    }



/**
* 判断一个对象是否存在key,如果传入第二个参数key,则是判断这个obj对象是否存在key这个属性
* 如果没有传入key这个参数,则判断obj对象是否有键值对
*/
   export const hasKey = (obj, key) => {
    if (key) return key in obj
    else {
      let keysArr = Object.keys(obj)
      return keysArr.length
    }
  }

import { hasKey } from '@/libs/tools'

this.hasKey =   hasKey({})  //0
this.hasKey =   hasKey({name:'徐文龙',id:'9090'})  //2
this.hasKey =   hasKey({name:'徐文龙',id:'9090'},'name') //true


/**
* @param {*} obj1 对象
* @param {*} obj2 对象
* @description 判断两个对象是否相等,这两个对象的值只能是数字或字符串
*/
export const objEqual = (obj1, obj2) => {
    const keysArr1 = Object.keys(obj1)
    const keysArr2 = Object.keys(obj2)
    if (keysArr1.length !== keysArr2.length) return false
    else if (keysArr1.length === 0 && keysArr2.length === 0) return true
    /* eslint-disable-next-line */
    else return !keysArr1.some(key => obj1[key] != obj2[key])
  }

  import { objEqual } from '@/libs/tools'
  this.objEqual = objEqual({name:'徐文龙',id:'xu',sex:'男'},{name:'徐文龙',id:'xu'})  //false
  this.objEqual = objEqual({name:'徐文龙',id:'xuwenlong'},{name:'徐文龙',id:'xuwenlong'}) //true



  /**
* 一个值如果是null或者''返回-
* @param value 需要处理的值
* @param length 需要截取的字符的长度的值,未指定的时候返回全部
* @returns {*} 处理过的值
*/
function replaceNull(value,length) {
    //判断截取的值是否为空
    if(value == null || value==undefined || value == "" || value=='undefined'){
        return "-";
    }
    //判断长度是否为空
    if(length == null || length == ''){
        return value;
    }
    return value.toString().substr(0,length);
}
this.replaceNull = replaceNull()   //"-"
this.replaceNull = replaceNull('2018-05-03',7)  //"2018-05"
this.replaceNull = replaceNull('2018-05-03',20)  //"2018-05-03"




/**
* @param {String} url
* @description 从URL中解析参数
*/
export const getParams = url => {
    const keyValueArr = url.split('?')[1].split('&')
    let paramObj = {}
    keyValueArr.forEach(item => {
      const keyValue = item.split('=')
      paramObj[keyValue[0]] = keyValue[1]
    })
    return paramObj
  }

  import { getParams} from '@/libs/tools'

  this.getParams  =getParams('SymberMgr/ReaByUser?sysName=SYS&rmbKey=通用字典记忆参数-A10003')
  //{sysName: "SYS", rmbKey: "通用字典记忆参数-A10003"}
  



  /**
* 10000 => "10,000" 金额格式化
* @param {number} num
*/
  export function toThousandFilter(num) {
    return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
  }

  import { toThousandFilter} from '@/libs/tools'

this.toTheousandFilter = toThousandFilter(27909087898.98989)
//"27,909,087,898.98989"
this.toTheousandFilter = toThousandFilter('27909087898.98989')
//"27,909,087,898.98989"
this.toTheousandFilter = toThousandFilter(279090878989)
//"279,090,878,989"


/**
* 大写首字符
* @param {String} string
*/
export function uppercaseFirst(string) {
    return string.charAt(0).toUpperCase() + string.slice(1)
}

import { uppercaseFirst} from '@/libs/tools'
this.uppercaseFirst = uppercaseFirst('xuwen_long')

//"Xuwen_long"
this.uppercaseFirst = uppercaseFirst('徐文龙')
//"徐文龙"

<div>{{ user.role | uppercaseFirst }}</div>





/**
* @param {string} input value 返回utf8字符串的字节长度
* @returns {number} output value
*/
export function byteLength(str) {
    let s = str.length
    for (var i = str.length - 1; i >= 0; i--) {
      const code = str.charCodeAt(i)
      if (code > 0x7f && code <= 0x7ff) s++
      else if (code > 0x7ff && code <= 0xffff) s += 2
      if (code >= 0xDC00 && code <= 0xDFFF) i--
    }
    return s
  }

  import { byteLength} from '@/libs/tools'

  this.byteLength = byteLength('xuwenlong_898989_6767')
//21




/**
* @returns {string} 生成唯一字符串
*/

export function createUniqueString() {
    const timestamp = +new Date() + ''
    const randomNum = parseInt((1 + Math.random()) * 65536) + ''
    return (+(randomNum + timestamp)).toString(32)
  }

  import { createUniqueString} from '@/libs/tools'

  this.createUniqueString = createUniqueString()
//"ubtkc3o9cb80"
this.createUniqueString = createUniqueString()
//"n2c4nsoekrs0"

  

posted @ 2019-07-11 18:45  龙旋风  阅读(382)  评论(14编辑  收藏  举报