项目中常用的工具函数(一)

        正所谓磨刀不误砍柴工,多次使用的方法,我们可以把其抽离出来,独立封装成一个函数,优化后续的便捷使用, 本篇文章主要介绍个人在工作中经常用到的一些工具类函数!!!

1、判断类型                                                           

export const getObjType = obj => {
  var toString = Object.prototype.toString;
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
};

2、序列化(适合post请求转为get请求)

export const serialize = data => {
  let list = [];
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&');
};

3、对象深拷贝

export const deepClone = data => {
  var type = getObjType(data);  // 见工具1
  var obj;
  if (type === 'array') {
    obj = [];
  } else if (type === 'object') {
    obj = {};
  } else {
    //不再具有下一层次
    return data;
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
};

4、设置灰度模式(一般用于“哀悼”置灰颜色)

export const toggleGrayMode = (status) => {
  if (status) {
    document.body.className = document.body.className + ' grayMode';
  } else {
    document.body.className = document.body.className.replace(' grayMode', '');
  }
};

.grayMode{
  filter: grayscale(100%);
}

5、加密处理

export const encryption = (params) => {
  let {data,type, param,key} = params;
  let result = JSON.parse(JSON.stringify(data));
  if (type == 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele]);
    })
  } else if (type == 'Aes') {
    param.forEach(ele => {
      result[ele] = window.CryptoJS.AES.encrypt(result[ele], key).toString();
    })

  }
  return result;
};

6、浏览器全屏类

/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen();
  } else {
    reqFullScreen();
  }
};

/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
  function listen() {
    callback()
  }

  document.addEventListener("fullscreenchange", function () {
    listen();
  });
  document.addEventListener("mozfullscreenchange", function () {
    listen();
  });
  document.addEventListener("webkitfullscreenchange", function () {
    listen();
  });
  document.addEventListener("msfullscreenchange", function () {
    listen();
  });
};

/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  var isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
  return isFullscreen;
}

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  }
};

/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen();
  }
};

7、递归寻找自己及子类

export const findParent = (menu, id) => {
    for (let i = 0; i < menu.length; i++) {
       if (menu[i].id === id) {
         return menu[i];
       }
       if (menu[i].children) {
         for (let j = 0; j < menu[i].children.length; j++) {
            const result = this.findParent(menu[i].children, id);
            if (result) {
              return result;
            }
          }
        }
      }
    return null;
}

8、判断是否相等(全类型)

export const diff = (obj1, obj2) => {
  delete obj1.close;
  var o1 = obj1 instanceof Object;
  var o2 = obj2 instanceof Object;
  if (!o1 || !o2) { /*  判断不是对象  */
    return obj1 === obj2;
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (var attr in obj1) {
    var t1 = obj1[attr] instanceof Object;
    var t2 = obj2[attr] instanceof Object;
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr]);
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
    }
  }
  return true;
}

9、生成随机len位数字或字母或验证码

/**
   @函数描述: 生成随机len位数字
   @param {bumber} len 长度
   @param {Boolean} isDate 是否需要添加时间戳
 */
export const randomLenNum = (len, isDate) => {
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
  if (isDate) random = random + Date.now();
  return random;
};

/**
 * 获取随机字符串
 * @param len 指定长度
 * @returns {string}
 */
export const randomString = (len) => {
  len = len || 32;
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  let maxPos = $chars.length;
  let pwd = '';
  for(let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

10、打开浏览器的小窗口

/**
 * 打开小窗口
 * @param url 窗口地址
 * @param title 窗口名称
 * @param w 窗口宽度
 * @param h 窗口高度
 */
export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height

  const left = ((width / 2) - (w / 2)) + dualScreenLeft
  const top = ((height / 2) - (h / 2)) + dualScreenTop
  const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus()
  }
}

11、获取顶部地址栏地址

export const getTopUrl = () => {
  return window.location.href.split("/#/")[0];
}

12、获取url参数

/**
 * 获取url参数
 * @param name 参数名
 */
getUrlParams(name) {
   const urlParams = new URLSearchParams(window.location.search);
   return urlParams.get(name);
}

/**
 * 获取url参数
 * @param name 参数名
 */
export const getQueryString = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(decodeURI(r[2]));
  return null;
}

13、校验对象是否有效

/**
 * 校验对象是否有效
 * 可校验null,undefined,空串,空数组,空对象
 * 注意:数值0返回true
 * @param obj
 * @returns {boolean}
 */
export const isNull = (obj) => {
  //所有数值都非NULL 数值0表示有效
  if (!isNaN(obj)) {
    return true;
  }
  //校验null,undefined,空字符串
  if ((!!obj) === false) {
    return false;
  }
  //校验数组
  if (Array.isArray(obj)) {
    return obj.length === 0;
  }
  //校验对象
  if (typeof (obj) === 'object') {
    return Object.keys(obj).length === 0;
  }
  throw new Error("无法识别的对象");
}

14、列表转tree

/**
 * 列表转树 由于有递归使用了匿名函数
 * @param arr 列表数据
 * @param rootId 根结点id
 * @returns {[]}
 */
export const arrayToTree = (function arrayToTree(arr, rootId = 0) {
  let temp = [];
  let treeArr = arr;
  treeArr.forEach((item, index) => {
      if (item.parentId === rootId) {
        if (arrayToTree(treeArr, treeArr[index].id).length > 0) {
          // 递归调用此函数
          treeArr[index].children = arrayToTree(treeArr, treeArr[index].id);
        }
        temp.push(treeArr[index]);
      }
    }
  );
  return temp;
});

To:面试题:扁平数据结构转Tree

 15、去掉评论输入框的style的样式

/**
 * 去掉复制文章时评论输入框的style的样式
 * @param stringStr 输入框的数据
 * @returns {HTMLDivElement}
 */
export const clearCommentStyle = (stringStr) => {
  return stringStr.replace(/<span\b[^>]*>/g, function(match) {
    // 使用正则表达式替换匹配到的 style 属性
    return match.replace(/style\s*=\s*["'][^"']*["']/g, '');
  });
}

16、导出文档(以.xlsx为例)

/**
 * 页面【导出】表格 - 【GET】
 * @param name 导出页面的名称
 * @param host 导出的地址
 * @returns {HTMLDivElement}
 */
export const downloadExportGet = (name,host) => {
  fetch(host, {
    method: 'GET',
    headers: {
      'System-Platform': 2,
      'Blade-Auth': getStore({name: 'token'})
    }
  })
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${name}-数据导出[${dateFormat()}].xlsx`;  // 下载的文件名
      a.click();
      window.URL.revokeObjectURL(url);
    });
}

/**
 * 页面【导出】表格 - 【POST】
 * @param name 导出页面的名称
 * @param host 导出的地址
 * @param data 请求的数据
 * @returns {HTMLDivElement}
 */
export const downloadExportPost = (name,host,data) => {
  fetch(host, {
    method: 'POST',
    headers: {
      'System-Platform': 2,
      'Blade-Auth': getStore({name: 'token'}),
      'Content-Type': 'application/json;charset=UTF-8'
    },
    body: JSON.stringify(data)
  })
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${name}-数据导出[${dateFormat()}].xlsx`;  // 下载的文件名
      a.click();
      window.URL.revokeObjectURL(url);
    });
}


window.open(`/api/base/dataPack/export?id=${id}`);

To:项目中导出文档数据

 下一章:项目中常用的工具函数(二)

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值