utils.js 8.34 KB
// 验证手机 以1开头的11位数字
export function checkMobile(str) {
  var pattern = /^1\d{10}$/;
  return pattern.test(str);
}


// 验证邮箱
export function checkEmail(email) {
  var pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return pattern.test(email);
}


// 判断是否微信环境
export function isWeiXin() {
  var ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
}

/**
 * 链接参数转换为obj
 * 入参 完整链接
 * @param {*} url 
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
    .replace(/"/g, '\\"')
    .replace(/&/g, '","')
    .replace(/=/g, '":"') +
    '"}'
  )
}


/**
 * 分转元
 * @param {*} fen
 * @returns
 */
export function regFenToYuan(fen) {
  var num = fen;
  num = fen * 0.01;
  num += '';
  var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
  num = num.replace(reg, '$1');
  num = toDecimal2(num)
  return num
};

/**
 * 元转分
 * @param {*} yuan
 * @param {*} digit
 * @returns
 */
export function regYuanToFen(yuan, digit = 100) {
  var m = 0,
    s1 = yuan.toString(),
    s2 = digit.toString();
  try {
    m += s1.split(".")[1].length
  } catch (e) {}
  try {
    m += s2.split(".")[1].length
  } catch (e) {}
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}


/**
 * 强制保留2位小数,如:2,会在2后面补上00.即2.00
 * @param {*} x
 * @returns
 */
export function toDecimal2(x) {
  var f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}

// 格式化星期几
export function formatWeek(week) {
  let result = "";
  switch (week) {
    case 1:
      result = "一";
      break;
    case 2:
      result = "二";
      break;
    case 3:
      result = "三";
      break;
    case 4:
      result = "四";
      break;
    case 5:
      result = "五";
      break;
    case 6:
      result = "六";
      break;
    case 0:
      result = "日";
      break;

    default:
      break;
  }
  return result;
}

// 数组去重
export function uniqueArr(arr, key) {
  let obj = {};
  let newArr = arr.reduce((cur, next) => {
    obj[next[key]] ? "" : obj[next[key]] = true && cur.push(next);
    return cur;
  }, [])
  return newArr
}


/**
 * 从数组中获取 key未value的对象
 * @param {*} value
 * @param {*} key
 * @param {*} list
 */
export function getObjByListKeyValue(value, key, list) {
  let result = null;
  list.forEach(element => {
    if (element[key + ""] == value) {
      result = element;
    }
  });
  return result;
}

/**
 * 获取环境信息
 * @return {Object} 环境信息对象
 */
export function getEnv() {
  var nav = window.navigator;
  var env = {
    "iphone": false,
    "ipad": false,
    "android": false,
    "pc": false,
    "ios": false,
    "ver": "0"
  };

  var ua = nav.userAgent;
  var android = ua.match(/(Android)\s+([\d.]+)/);
  var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  if (ipad) {
    env.ipad = ipad[1] && true || false;
    env.ver = ipad[2] && ipad[2].replace(/-/g, ".") || "";
    env.ios = true;
  } else if (iphone) {
    env.iphone = iphone[1] && true || false;
    env.ver = iphone[2] && iphone[2].replace(/-/g, ".") || "";
    env.ios = true;
  } else if (android) {
    env.android = android[1] && true || false;
    env.ver = android[2];
  } else {
    env.pc = true;
  }

  return env;
}

/**
 * 设定页面 title
 * @param {[type]} title [description]
 */
export function setTitle(title) {
  if (!title) {
    return;
  }
  document.title = title;
  // if (ENV.ios && navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1) {
  // 修复微信端IOS无法修改document.title的情况
  if (getEnv().ios && (navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1 || navigator.userAgent.toLowerCase().indexOf("alipay") !== -1)) {
    //修复IOS微信端和支付宝无法修改document.title的情况
    var $iframe = document.createElement('iframe');
    $iframe.className = "C-hiddenIframe";
    $iframe.src = "/" + location.pathname.split('/')[1] + "/favicon.ico";
    $iframe.style.visibility = 'hidden';
    $iframe.style.width = '1px';
    $iframe.style.height = '1px';
    $iframe.onload = function onIframeLoad() {
      setTimeout(function () {
        $iframe.onload = null;
        onIframeLoad = null;
        document.body.removeChild($iframe);
        $iframe = null;
      }, 0);
    };
    document.body.appendChild($iframe);
  }
}

// 为链接添加参数
export function addQuery(url, query) {
  query = query || {}
  query = (function (query) {
    var q = []
    Object.keys(query).forEach(function (_q) {
      q.push(_q + '=' + query[_q])
    })
    return q.join('&')
  })(query)
  if (url.indexOf('?') !== -1) {
    url += '&' + query
  } else {
    url += '?' + query
  }
  return url
}


/**
 * 获得当前页面的path
 * @return {String} 页面path
 */
export function getPath() {
  var path = window.location.hash;
  path = path || "#/";
  path = path === "#/" ? "#/index" : path;
  path = path.split("?");
  return path[0];
}

// 获取 url 参数
export function getQuery(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
}

/**
 * 把 \n换行符转换成<br>
 * 转换后需要用 v-html渲染
 * 用{{}}会当成字符串把 html渲染出来
 */
export function formatBr(str) {
  str = str.replace(/\n/g, '<br/>')
  return str
};

/**
 * 格式化日期时间 支持Date和时间戳
 * @param {date} date 日期时间
 * @param {string} fmt 格式,如:'yyyy-MM-dd hh:mm:ss'
 */
export function formatDate(date, fmt) {
  if (!date) return '-'
  // 把-换成/ 避免iOS和安卓真机问题
  var reg = /-/g;
  if (typeof date == 'object') {
    date += "";
    date = date && date.replace(reg, '/');
  }
  date = new Date(date)
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (const 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
}







/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
let debounceTimeout;

export function debounce(func, wait, immediate) {
  return function () {
    let context = this;
    let args = arguments;

    if (debounceTimeout) clearTimeout(debounceTimeout);
    if (immediate) {
      var callNow = !debounceTimeout;
      debounceTimeout = setTimeout(() => {
        debounceTimeout = null;
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      debounceTimeout = setTimeout(function () {
        func.apply(context, args)
      }, wait);
    }
  }();
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版,2 表定时器版
 * 时间戳版的函数触发是在时间段内开始的时候,而定时器版的函数触发是在时间段内结束的时候。
 */
let throttleTimeout;
let throttlePrevious;

export function throttle(func, wait, type) {
  if (type === 1) {
    throttlePrevious = 0;
  } else if (type === 2) {
    throttleTimeout = 0;
  }
  return function () {
    let context = this;
    let args = arguments;
    if (type === 1) {
      let now = Date.now();

      if (now - throttlePrevious > wait) {
        func.apply(context, args);
        throttlePrevious = now;
      }
    } else if (type === 2) {
      if (!throttleTimeout) {
        throttleTimeout = setTimeout(() => {
          throttleTimeout = null;
          func.apply(context, args)
        }, wait)
      }
    }
  }();
}