项目实用方法

导出表(后端返回,前端导出)


	// 下载文件
	function downloadFile(blob, name, suffix) {
	  const url = window.URL.createObjectURL(new Blob([blob]))
	  const link = document.createElement('a')
	  link.style.display = 'none'
	  link.href = url
	  const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
	  link.setAttribute('download', fileName)
	  document.body.appendChild(link)
	  link.click()
	  document.body.removeChild(link)
	}

树结构转二维数组


	   function TreeToArr(tree) {
          let result = [] // 结果
          function getPath(node, arr) {
             arr.push(node.id)
             if (node.children?.length > 0) { // 存在多个节点就递归
               node.children.forEach(v2 => getPath(v2, [...arr]))
               } else {
                result.push(arr)
               }
            }
            tree.forEach(v => getPath(v, []))
            return result
        }

替换手机号中间四位(159****4545)

	function regMobile(mobile) {
	  if (mobile.length > 7) {
	    var new_mobile = mobile.substr(0, 3) + '****' + mobile.substr(7)
	  }
	  return new_mobile
	}

递归克隆数组对象

	function deepClone(obj) {
	  if (!obj&& typeof obj!== 'object') {
	    throw new Error('error arguments', 'deepClone')
	  }
	  const targetObj = obj.constructor === Array ? [] : {}
	  Object.keys(obj).forEach(keys => {
	    if (obj[keys] && typeof obj[keys] === 'object') {
	      targetObj[keys] = deepClone(obj[keys])
	    } else {
	      targetObj[keys] = obj[keys]
	    }
	  })
	  return targetObj
	}

将字符串转大写

	const hyphenateRE = /\B([A-Z])/g
	const hyphenate =(str)=> {
	  return str.replace(hyphenateRE, '-$1').toLowerCase()
	}

判断;两个对象或数组是否相等

/**
 * 
 * 判断两个对象或数组是否相等
 */
function looseEqual (a, b): boolean {
  if (a === b) return true
  const isObjectA = a!== null && typeof a=== 'object'
  const isObjectB = b!== null && typeof b=== 'object'
  if (isObjectA && isObjectB) {
    try {
      const isArrayA = Array.isArray(a)
      const isArrayB = Array.isArray(b)
      if (isArrayA && isArrayB) {
        return a.length === b.length && a.every((e, i) => {
          return looseEqual(e, b[i])
        })
      } else if (a instanceof Date && b instanceof Date) {
        return a.getTime() === b.getTime()
      } else if (!isArrayA && !isArrayB) {
        const keysA = Object.keys(a)
        const keysB = Object.keys(b)
        return keysA.length === keysB.length && keysA.every(key => {
          return looseEqual(a[key], b[key])
        })
      } else {
        return false
      }
    } catch (e) {
      return false
    }
  } else if (!isObjectA && !isObjectB) {
    return String(a) === String(b)
  } else {
    return false
  }
}

防抖函数

	    /**
     * 防抖函数
     * @param method 事件触发的操作
     * @param delay 多少毫秒内连续触发事件,不会执行
     * @returns {Function}
     */
    function debounce(method, delay) {
        let timer = null;
        return function () {
            let self = this;
            let args = arguments;
            timer && clearTimeout(timer);
            timer = setTimeout(function () {
                method.apply(self, args);
            },delay);
        }
    }

节流函数

	
    /**
     * 节流函数
     * @param method 事件触发的操作
     * @param mustRunDelay 间隔多少毫秒需要触发一次事件
     */
    function throttle(method, mustRunDelay) {
        let timer;
        let start;
        return function loop() {
            let self = this;
            let now = Date.now();
            let args = arguments;
            if(!start){
                start = now;
            }
            if(timer){
                clearTimeout(timer);
            }
            if(now - start >= mustRunDelay){
                method.apply(self, args);
                start = now;
            }else {
                timer = setTimeout(function () {
                    loop.apply(self, args);
                }, 50);
            }
        }
    }

文件转base64

    /**
     * 文件对象转base64字符串
     * @param {File} file 文件对象
     * @return {Promise<any>}
     */
    function convertFileToBase64(file) {
        return new Promise((resolve, reject) => {
            let fileReader = new FileReader();
            fileReader.onload = () => {
                resolve(fileReader.result);
            };
            fileReader.onerror = (error) => {
                reject(error);
            };
            fileReader.readAsDataURL(file);
        })
    }

base64转file对象

	    /**
     * 将base64转成file对象
     * @param base64 {String} 带mime前缀的base64字符串
     * @param fileName {String} 文件名(后缀强制为mime类型)
     * @return {File}
     */
    function convertBase64ToFile(base64, fileName) {
        let arr = base64.split(',');
        let mime = arr[0].match(/:(.*?);/)[1];
        let bstr = window.atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], fileName, {type:mime});
    }

文件直接下载

	    /**
     * 浏览器直接下载文件
     * @param blob {File | Blob} 文件blob | file 对象
     * @param fileName {String} 文件名
     */
    function download(blob, fileName) {
        if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a');
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = window.URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            window.URL.revokeObjectURL(elink.href) ;
            document.body.removeChild(elink);
        } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName);
        }
    },

常见的正则表达式

	//简易手机号
const easyMobilePhone = /^1\d{10}$/;
//手机号
const mobilePhone = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9])|(19[0-9]))\d{8}$/;
//国内座机
const telephone = /\d{3}-\d{8}|\d{4}-\d{7}/;
//身份证
const idCard = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
//ipV4
const ipV4 = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
//十六进制
const hex = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
//QQ号码
const QQ = /^[1-9][0-9]{4,10}$/;
//微信号码
const WX = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/;
//包含中文
const includeCN = /[\u4E00-\u9FA5]/;
//只有中文
const onlyCN = /^[\u4e00-\u9fa5]*$/;
//URL
const URL = /^(https?:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i;
//HTTP
const HTTP = /^(http:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i;
//HTTPS
const HTTPS = /^(https:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i;
//中国邮政编码
const postalCode = /[1-9]\d{5}(?!\d)/;
//邮箱验证
const email = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值