util.js 4.12 KB
import Vue from 'vue'
import { Toast, Dialog } from 'vant'

/**
 * 日期格式化
 * let time = new Date().format('yyyy-MM-dd hh:mm:ss')
 */
Date.prototype.format = function (fmt) {
  let o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    //季度
    'q+': Math.floor((this.getMonth() + 3) / 3),
    S: this.getMilliseconds() //毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return fmt
}
const throttle = (fn, delay = 1000) => {
  // 距离上一次的执行时间
  let lastTime = 0
  return function () {
    const _this = this
    const _arguments = arguments
    const now = new Date().getTime()
    // 如果距离上一次执行超过了delay才能再次执行
    if (now - lastTime > delay) {
      fn.apply(_this, _arguments)
      lastTime = now
    }
  }
}

/**num:要转换的数值,fixed:精确几位小数 */
const decimal = (num, fixed) => {
  let pow = Math.pow(10, fixed)
  return Math.round(num * pow) / pow
}

const toTop = () => {
  let bodySrcollTop = document.body.scrollTop
  if (bodySrcollTop !== 0) {
    document.body.scrollTop = 0
    return
  }
  let docSrcollTop = document.documentElement.scrollTop
  if (docSrcollTop !== 0) {
    document.documentElement.scrollTop = 0
  }
}
const getParams = () => {
  return window.vm.$route.params
}
const getQuery = name => {
  let [url, paramsList] = window.location.href.split('?')
  if (!paramsList) return name ? null : {}
  let param = paramsList.split('&')
  let obj = {}
  param.map(e => {
    let [key, value] = e.split('=')
    obj[key] = value
  })
  return name ? obj[name] : obj
}

/** 三个数字加一个逗号 */
const numAddSymbol = val => {
  return val ? (val + '').replace(/\B(?=(?:\d{3})+\b)/g, ',') : 0
}

// 获取当前时间
const getCurrentDate = (fmt = 'yyyy-MM-dd') => {
  return new Date().format(fmt)
}

/** 获取前/后n天
 * 负数:今天前n天
 * 正数:今天后n天
 */
const getNDate = (n, fmt = 'yyyy-MM-dd') => {
  return new Date(new Date().setDate(new Date().getDate() + n)).format(fmt)
}

/** 获取前/后n月
 * 负数:今天前n月
 * 正数:今天后n月
 */
const getNMonth = (n, fmt = 'yyyy-MM-dd') => {
  return new Date(new Date().setMonth(new Date().getMonth() + n)).format(fmt)
}

const debounce = function (func, wait = 200) {
  let timeout
  return function (event) {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.call(this, event)
    }, wait)
  }
}
const setChartFontSize = fontSize => {
  let clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
  if (!clientWidth) return fontSize
  return (fontSize * clientWidth) / 1440
}
const deepClone = obj => {
  // Handle the 3 simple types, and null or undefined or function
  if (obj == null || typeof obj !== 'object') return obj
  // Handle Date
  if (obj instanceof Date) {
    const copy = new Date()
    copy.setTime(obj.getTime())
    return copy
  }
  // Handle Array or Object
  if ((obj instanceof Array) | (obj instanceof Object)) {
    const copy = obj instanceof Array ? [] : {}
    for (var attr in obj) {
      if (obj.hasOwnProperty(attr)) {
        copy[attr] = deepClone(obj[attr])
      }
    }
    return copy
  }
  throw new Error("Unable to clone obj! Its type isn't supported.")
}
// 数字转百分数
const toPercent = num => {
  let str = Number(num).toFixed(0)
  str += '%'
  return str
}
const utils = {
  getParams,
  getQuery,
  throttle,
  decimal,
  toTop,
  numAddSymbol,
  getCurrentDate,
  getNDate,
  getNMonth,
  debounce,
  setChartFontSize,
  deepClone,
  toPercent
}

Object.keys(utils).map(key => {
  Vue.prototype[key] = utils[key]
})
export default utils