util.js 3.83 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 WindowEvent = (type, callBack) => {
  if (window.attachEvent) {
    window.attachEvent(`on${type}`, function () {
      callBack.call(window);
    });
  } else {
    window.addEventListener(type, callBack, false);
  }
};
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 noScroll = (e) => { e.preventDefault() }
const showLoading = (title = "加载中...") => {
  Toast({
    type: "loading",
    message: title,
    forbidClick: true,
    duration: 0,
  });
};

/**监听页面滚动事件 */
const onPageScroll = (callBack) => {
  WindowEvent("scroll", ($event) => {
    return callBack($event);
  });
};
/**num:要转换的数值,fixed:精确几位小数 */
const decimal = (num, fixed) => {
  let pow = Math.pow(10, fixed);
  return Math.round(num * pow) / pow;
};
const isMobileDevice = () => {
  //判断当前设备是否为移动端
  const ua = navigator.userAgent.toLowerCase();
  const t1 =
    /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ua);
  const t2 = !ua.match("iphone") && navigator.maxTouchPoints > 1;
  return t1 || t2;
};
const showToast = (title = "") => {
  Toast({
    duration: 1500,
    message: title,
    forbidClick: true,
  });
};
/**触摸样式 */
const touchstart = (e) => {
  e.target.classList.add("btn-on-leave");
};
const touchend = (e) => {
  e.target.classList.remove("btn-on-leave");
};
/**dialog弹框 */
const dialog = (message, callBack) => {
  Dialog.alert({
    message,
  }).then(() => {
    callBack();
  });
};
/**
 * 时间戳转化为年 月 日 时 分 秒
 * ts: 传入时间戳
 * format:返回格式,支持自定义,但参数必须与formateArr里保持一致
 */
const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : "0" + n;
};
const hideLoading = () => {
  Toast.clear();
};
const tsFormatTime = (timestamp, format) => {
  format = format || "Y-M-D h:m:s";
  const formateArr = ["Y", "M", "D", "h", "m", "s"];
  let returnArr = [];

  let date = new Date(timestamp);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();
  returnArr.push(year, month, day, hour, minute, second);

  returnArr = returnArr.map(formatNumber);

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
};
const getLocalStorage = (key) => {
  return JSON.parse(window.localStorage.getItem(key));
};
const utils = {
  getLocalStorage,
  onPageScroll,
  showLoading,
  hideLoading,
  touchstart,
  showToast,
  throttle,
  touchend,
  decimal,
  dialog,
  isMobileDevice,
  tsFormatTime,
};

export default { utils };

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