常用的封装工具方法

42 阅读1分钟

1、一个通用方法, 一行代码获取 各种数据的类型

const getType = (data) => {
  return Object.prototype.toString.call(data)
    .slice(8, -1)
    .toLocaleLowerCase()
}

let a ={}
getType(a)//'object'

function b(){}
getType(b)//'function'

getType(111)//'number'

let c = null
getType(c)//'null'

let d = undefined
getType(d)//'undefined'

let f = [1]
getType(f)//'array'

Object.prototype.toString.call() 方法返回一个表示该对象的字符串, 该字符串格式为 "[object Type]", 这里的 Type 就是对象的类型

const toString = Object.prototype.toString;

toString.call(111); // [object Number]
toString.call(null); // [object Null]
toString.call(undefined); // [object Undefined]

toString.call(Math); // [object Math]
toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]

参考文章juejin.cn/post/724677…

2、嵌套的数组对象深拷贝

export function deepClone(obj, newObj) {
  var newObj = newObj || {};
  for (let key in obj) {
      if (typeof obj[key] == 'object') {
          let isArray = Array.isArray(obj[key]);//判断是否数组
          newObj[key] = (isArray == true ? [] : {})
          deepClone(obj[key], newObj[key]);
      } else {
          newObj[key] = obj[key]
      }
  }
  return newObj;
}

3、金额格式化:千分位分隔,保留2位小数

 // 数字,千分位,保留2位小数
export const formatterNumber = (data: number) => {
  return (
    data?.toLocaleString('zh', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }) || data
  )
}

4、通过后端返回的Url实现文件下载

 // 下载
export const download_file = (baseUrl:string, fileName:string, idList?:any) => {
    const x = new window.XMLHttpRequest()
    x.open('POST', baseUrl, true)
    x.setRequestHeader("Authorization",`Bearer ${localStorage.getItem('token')}`)
    x.setRequestHeader('content-type', 'application/json; charset=UTF-8');
    x.responseType = 'blob'
    x.onload = () => {
      const url = window.URL.createObjectURL(x.response)
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      a.style.display = "none"; // 障眼法藏起来a标签
      document.body.appendChild(a);// 将a标签追加到文档对象中 
      a.click()
      a.remove();// 一次性的,用完就删除a标签 
    }
    if(idList){
      let data = JSON.stringify(idList);
      x.send(data)
    }else{
      x.send()
    }
    
}

5、通过后端返回的字符串实现文件下载

 
export const downloadBlob = (data: string, filename: string, type: string): void => {
  const blob = new Blob([data]);
  const tempLink = document.createElement('a'); // 创建a标签
  const href = window.URL.createObjectURL(blob); // 创建下载的链接
  //filename
  const fileName = `${filename}.${type}`;
  tempLink.href = href;
  tempLink.target = '_blank';
  tempLink.download = fileName;
  document.body.appendChild(tempLink);
  tempLink.click(); // 点击下载
  document.body.removeChild(tempLink); // 下载完成移除元素
  window.URL.revokeObjectURL(href); // 释放掉blob对象
};