util.js 9.97 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 iosTimeFormat = time => {
  return time.replace(/-/g, '/')
}
const throttle = (fn, gapTime) => {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }
  let _lastTime = null
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments)
      _lastTime = _nowTime
    }
  }
}
const debounce = (fn, delay = 500) => {
  // timer 是在闭包中的
  let timer = null
  return function () {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}
/**防止重复点击 */
const showLoading = (title = '加载中...') => {
  Toast({
    type: 'loading',
    message: title,
    forbidClick: true,
    duration: 0
  })
}
const hideLoading = () => {
  Toast.clear()
}
/**num:要转换的数值,fixed:精确几位小数 */
const decimal = (num, fixed = 2) => {
  let pow = Math.pow(10, fixed)
  return Math.round(num * pow) / pow
}
const showToast = (message = '', callBack) => {
  hideLoading()
  let params = {
    message,
    forbidClick: true,
    duration: 1500
  }
  Toast(params)
  if (callBack && typeof callBack == 'function') {
    setTimeout(() => {
      callBack()
    }, 1500)
  }
}
/**触摸样式 */
const touchstart = e => {
  e.target.classList.add('btn-on-leave')
}
const touchend = e => {
  e.target.classList.remove('btn-on-leave')
}
const setSessionId = val => {
  window.localStorage.setItem('wx_scrm_session_id', val)
}
const getSessionId = () => {
  return window.localStorage.getItem('wx_scrm_session_id')
}
const clearSessionId = () => {
  window.localStorage.removeItem('wx_scrm_session_id')
  window.localStorage.removeItem('dj_scrm_session_id')
}
const setAppId = val => {
  window.localStorage.setItem('wx_scrm_app_id', val)
}
const getAppId = () => {
  return window.localStorage.getItem('wx_scrm_app_id')
}
const setUserInfo = val => {
  setLocalStorage('wx_scrm_user_info', val)
}
const getUserInfo = () => {
  return getLocalStorage('wx_scrm_user_info')
}
const setLocalStorage = (key, item) => {
  window.localStorage.setItem(key, JSON.stringify(item))
}
const getLocalStorage = key => {
  let store = JSON.parse(window.localStorage.getItem(key))
  if (key == 'wx_scrm_link_params') {
    if (!store || Object.keys(store).length < 0) {
      store = getPageQuery()
    }
  }
  return store
}
const getPageQuery = 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 removeLocalStorage = key => {
  window.localStorage.removeItem(key)
}
const dialog = (params = {}) => {
  if (!params.confirmButtonColor) params.confirmButtonColor = '#FF7336'
  return Dialog.confirm(params)
}
/**拨打电话 */
const makePhoneCall = phoneNumber => {
  window.location.href = `tel://${phoneNumber}`
}
/**是否全面屏 */
const isFullSucreen = () => {
  let result = false
  const rate = window.screen.height / window.screen.width
  let limit = window.screen.height == window.screen.availHeight ? 1.8 : 1.65 // 临界判断值
  result = rate > limit
  return result
}

const jumpChildrenPage = (to, params) => {
  let { name } = window.vm._route
  window.vm.$router.push({ name: `${name}.${to}`, params })
}
/**拷贝 */
const setClipboardData = data => {
  wx.setClipboardData({
    data,
    success (res) {
      Toast('复制成功')
    }
  })
}

/**接口请求时失败让用户刷新 */
const refreshPage = (message = '系统异常', confirmButtonText) => {
  return Dialog.alert({
    message,
    theme: 'round-button',
    confirmButtonText: confirmButtonText || '点击重试',
    confirmButtonColor: '#f13c3d'
  })
}
const toTop = (top = 0) => {
  window.scrollTo({
    top,
    left: 0,
    behavior: 'smooth'
  })
}
const getParams = name => {
  return name ? window.vm.$route.params[name] : window.vm.$route.params
}
const getQuery = () => {
  return window.vm.$route.query
}
const watchPageBack = () => {
  return new Promise(resolve => {
    if (window.$back) {
      window.$back = false
      resolve()
    }
  })
}
/**分转元 */
const centsToyuan = price => {
  return decimal(Number(price) / 100, 2).toFixed(2)
}
/**设置cookie */
const setCookie = (c_name, value, expiredays = 365) => {
  let exdate = new Date()
  console.log(c_name, value)
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = c_name + '=' + value + (expiredays == null ? '' : ';expires=' + exdate.toGMTString())
}
/**获取cookie */
const getCookie = c_name => {
  if (document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(c_name + '=')
    if (c_start != -1) {
      c_start = c_start + c_name.length + 1
      let c_end = document.cookie.indexOf(';', c_start)
      if (c_end == -1) c_end = document.cookie.length
      return unescape(document.cookie.substring(c_start, c_end))
    }
  }
  return ''
}
/*转中文 */
const toUnicode = (chineseStr = '') => {
  let unicodeStr = ''
  for (let i = 0, iLength = chineseStr.length; i < iLength; i++) {
    unicodeStr += '@' + chineseStr.charCodeAt(i).toString(16)
  }
  return unicodeStr
}
const isMobileDevice = () => {
  //判断当前设备是否为移动端
  const ua = navigator.userAgent.toLowerCase()
  const t1 = /android|webos|iphone|ipad|ipod|blackberry|iemobile|OpenHarmony|Harmony|opera mini/i.test(ua)
  const t2 = !ua.match('iphone') && navigator.maxTouchPoints > 1
  return t1 || t2
}

/**秒数转天时分秒*/
const date_format = num => {
  const addZero = i => (i < 10 ? `0${i}` : `${i}`)
  //计算剩余的天数
  let days = addZero(parseInt(num / 60 / 60 / 24, 10))
  //计算剩余的小时
  let hours = addZero(parseInt((num / 60 / 60) % 24, 10))
  //计算剩余的分钟
  let minutes = addZero(parseInt((num / 60) % 60, 10))
  //计算剩余的秒数
  let second = addZero(parseInt(num % 60, 10))
  if (days == 0) {
    return `${hours}:${minutes}:${second}`
  }
  return `${days}天${hours}:${minutes}:${second}`
}
const draggable = (drag, fun, target) => {
  var startEvt, moveEvt, endEvt
  // 判断是否支持触摸事件
  if ('ontouchstart' in window) {
    startEvt = 'touchstart'
    moveEvt = 'touchmove'
    endEvt = 'touchend'
  } else {
    startEvt = 'mousedown'
    moveEvt = 'mousemove'
    endEvt = 'mouseup'
  }
  drag.style.cursor = 'grab'
  var disX, disY, left, top, starX, starY, oLeft, oTop
  drag.addEventListener(startEvt, startFun)

  function startFun (event) {
    // console.log('event', )
    let className = event.target.className
    if (!drag.id || className.includes(target)) return
    // 阻止页面的滚动,缩放
    event.preventDefault()
    // 兼容IE浏览器
    drag.style.cursor = 'grabbing'
    var e = event || window.event
    oLeft = drag.offsetLeft
    oTop = drag.offsetTop
    // 手指按下时的坐标
    starX = e.touches ? e.touches[0].clientX : e.clientX
    starY = e.touches ? e.touches[0].clientY : e.clientY
    // 手指相对于拖动元素左上角的位置
    disX = starX - drag.offsetLeft
    disY = starY - drag.offsetTop
    // 按下之后才监听后续事件
    document.addEventListener(moveEvt, moveFun)
    document.addEventListener(endEvt, endFun)
  }

  function moveFun (event) {
    // 兼容IE浏览器
    var e = event || window.event
    left = (e.touches ? e.touches[0].clientX : e.clientX) - disX
    top = (e.touches ? e.touches[0].clientY : e.clientY) - disY
    // 限制拖拽的X范围,不能拖出屏幕
    if (left < 0) {
      left = 0
    } else if (left > document.documentElement.clientWidth - drag.offsetWidth) {
      left = document.documentElement.clientWidth - drag.offsetWidth
    }
    // 限制拖拽的Y范围,不能拖出屏幕
    if (top < 0) {
      top = 0
    } else if (top > window.innerHeight - drag.offsetHeight) {
      top = window.innerHeight - drag.offsetHeight
    }
    drag.style.left = left + 'px'
    drag.style.top = top + 'px'
  }
  function endFun (event) {
    drag.style.cursor = ''
    document.removeEventListener(moveEvt, moveFun)
    document.removeEventListener(endEvt, endFun)
    if (oLeft == drag.offsetLeft && oTop == drag.offsetTop && fun) {
      // 点击
      fun()
    }
  }
}
const clearObjNull = options => {
  let obj = {}
  Object.keys(options).map(e => {
    if (options[e] != null && options[e] != undefined) {
      if (typeof options[e] == 'object') {
        Object.keys(options[e]).map(key => {
          if (options[e][key] == null || options[e][key] == undefined) delete options[e][key]
        })
      }
      obj[e] = options[e]
    }
  })
  return obj
}

const utils = {
  removeLocalStorage,
  setClipboardData,
  jumpChildrenPage,
  setLocalStorage,
  getLocalStorage,
  clearSessionId,
  isMobileDevice,
  makePhoneCall,
  isFullSucreen,
  watchPageBack,
  iosTimeFormat,
  setSessionId,
  getPageQuery,
  getSessionId,
  clearObjNull,
  showLoading,
  centsToyuan,
  setUserInfo,
  getUserInfo,
  hideLoading,
  refreshPage,
  date_format,
  touchstart,
  showToast,
  getParams,
  toUnicode,
  setCookie,
  getCookie,
  draggable,
  setAppId,
  getAppId,
  debounce,
  getQuery,
  touchend,
  throttle,
  decimal,
  dialog,
  toTop
}

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