vue常用工具函数封装(一)

202 阅读2分钟

1、时间日期格式化

/**
 * 将时间格式化
 * @param time 传入的内容可以为 new Date() 或者 '2022-8-15 13:23:59' 或者 时间戳
 * @param cFormat  需要转化为此的时间格式  例如:"{y}年{m}月{d}日 {h}时{i}分{s}秒 周{a}"
 */
export function parseTime(time, cFormat) {
  if (!time) return "";
  if (arguments.length === 0) return null;
  // 如果cFormat不存在,则默认时间格式(cFormat传参参照如此)
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  // 判断是否为时间格式
  if (typeof time === "object") {
    date = time;
  } else {
    // 如果是数字字符串,则先转为数字
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    // 如果时间戳为秒,则转为毫秒
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  // 先罗列获取对应时间的计算方式
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    // 将匹配到的字符赋值相应的计算时间
    const value = formatObj[key];
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    // 个位数往前面补0
    return value.toString().padStart(2, "0");
  });
  return timeStr;
}

2、下载文件

/**
 * 下载文件,例如:downloadFile("你好!", "测试文件名称", "txt");
 *
 * @param obj 文件内容
 * @param name 下载的文件名称
 * @param suffix 下载的文件后缀名如('txt','xlsx')
 */
export function downloadFile(url, name, suffix) {
  const newUrl = url;
  const link = document.createElement("a");
  link.style.display = "none";
  link.href = newUrl;
  const fileName = name + "." + suffix;
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

3、手机号脱敏

export const hideMobile = (mobile) => { return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2") }

4、防抖

export const debounce = (() => {
  let timer = null
  return (callback, wait = 500) => {
    timer&&clearTimeout(timer)
    timer = setTimeout(callback, wait)
  }
})()
// 使用方法
methods: {
  requerstList() {
    debounce(() => {
      console.log('请求数据')
    }, 500)
  }
}

4、节流

export const throttleFcn = (() => {
  let last = 0
  return (callback, wait = 800) => {
    let now = +new Date()
    if (now - last > wait) {
      callback()
      last = now
    }
  }
})()
// 使用方法
methods: {
  requerstList() {
    throttleFcn(() => {
      console.log('请求数据')
    }, 800)
  }
}

5、大小写转换

/** 
  *参数:
  *str 待转换的字符串
  *type 1-全大写 2-全小写 3-首字母大写
  */
export const turnCase = (str, type) => {
  switch (type) {
    case 1:
      return str.toUpperCase()
    case 2:
      return str.toLowerCase()
    case 3:
      //return str[0].toUpperCase() + str.substr(1).toLowerCase() // substr 已不推荐使用
      return str[0].toUpperCase() + str.substring(1).toLowerCase()
    default:
      return str
  }
}

6、解析地址URL参数

export const getSearchParams = () => {
  const searchParams = new URLSearchParams(window.location.search)
  const paramsObj = {}
  for (const [key, value] of searchParams.entries()) {
    paramsObj[key] = value
  }
  return paramsObj
}

7、判断手机是Andoird还是IOS

/** 
 * 1: ios
 * 2: android
 * 3: 其它
 */
export const getOSType=() => {
  let u = navigator.userAgent, app = navigator.appVersion;
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  if (isIOS) {
    return 1;
  }
  if (isAndroid) {
    return 2;
  }
  return 3;
}

8、数组对象根据字段去重

/** 
*参数:
*arr 要去重的数组
*key 根据去重的字段名
 */


export const uniqueArrayObject = (arr = [], key = 'id') => {
  if (arr.length === 0) return
  let list = []
  const map = {}
  arr.forEach((item) => {
    if (!map[item[key]]) {
      map[item[key]] = item
    }
  })
  list = Object.values(map)

  return list
}

9、 滚动到页面顶部

export const scrollToTop = () => {
  const height = document.documentElement.scrollTop || document.body.scrollTop;
  if (height > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, height - height / 8);
  }
}

10、滚动到元素位置

// behavior[可选]定义过渡动画。"auto","instant"或"smooth"。默认为"auto"。

export const smoothScroll = element =>{
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth'
    });
};
// smoothScroll('#target');

11、金额格式化

/**
*参数:
*{number} number:要格式化的数字
*{number} decimals:保留几位小数
*{string} dec_point:小数点符号
*{string} thousands_sep:千分位符号
*/

export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
  const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
  const dec = typeof dec_point === 'undefined' ? '.' : dec_point
  let s = ''
  const toFixedFix = function(n, prec) {
    const k = Math.pow(10, prec)
    return '' + Math.ceil(n * k) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  const re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

12、 深拷贝

// 如果确实想要完备的深拷贝,推荐使用 lodash 中的 cloneDeep 方法

13、 遍历树节点

export const foreachTree = (data, callback, childrenName = 'children') => {
  for (let i = 0; i < data.length; i++) {
    callback(data[i])
    if (data[i][childrenName] && data[i][childrenName].length > 0) {
      foreachTree(data[i][childrenName], callback, childrenName)
    }
  }
}