前端项目常用的工具类函数

10 篇文章 0 订阅
8 篇文章 0 订阅

话不多说上代码!!!

import axios from 'axios';
/**
 * 两个数字相除
 * @param {number} n 因为0/0等于NaN
 */
export const notZero = (m, n) => {
  if (!n || !m) {
    // Matches +0, -0, NaN
    return 0;
  }
  return m / n;
};

/**
 * 下载文件
 * @param {String} filename 文件名:登录.txt
 * @param {String} content 内容
 * @param {*} contentType
 */
export const download = (filename, content, contentType) => {
  if (!contentType) contentType = 'application/octet-stream';
  var a = document.createElement('a');
  var blob = new Blob([content], { type: contentType });
  a.href = window.URL.createObjectURL(blob);
  a.download = filename;
  a.click();
};

/**
 * 判断value,是不是为数字类型
 * true:数值型的,false:非数值型
 * @param {*} value
 */
export const valueIsNaN = (value) => {
  return typeof value === 'number' && !isNaN(value);
};

/**
 * 小进度条插件,添加进度条
 * @param {Nprogress} nprogress
 */
export const nprogressschedule = (nprogress) => {
  for (let index = 0; index < 8; index++) {
    if (index === 0) {
      nprogress.set(0.3 + index * 0.1);
    } else if (index === 1) {
      setTimeout(() => {
        nprogress.set(0.3 + index * 0.1);
      }, 200);
    } else if (index === 2) {
      setTimeout(() => {
        nprogress.set(0.3 + index * 0.1);
      }, 400);
    } else if (index === 3) {
      setTimeout(() => {
        nprogress.set(0.3 + index * 0.1);
      }, 450);
    } else if (index === 4) {
      setTimeout(() => {
        nprogress.set(0.3 + index * 0.1);
      }, 500);
    } else if (index === 5) {
      setTimeout(() => {
        nprogress.set(0.3 + index * 0.1);
      }, 550);
    } else if (index === 6) {
      setTimeout(() => {
        nprogress.set(0.3 + index * 0.1);
      }, 600);
    } else if (index === 7) {
      setTimeout(() => {
        nprogress.set(1);
      }, 700);
    }
  }
};

export const getVal = (obj, ...args) => {
  let out = null;
  if (obj || obj === 0) {
    out = obj;
    if (args && args.length > 0) {
      for (let index = 0; index < args.length; index++) {
        const key = args[index];
        out = out[key];
        if (out === undefined || out === null || out === '') {
          return null;
        }
      }
    } else {
      if (out === undefined || out === null || out === '') {
        return null;
      }
    }
  }
  return out;
};

/**
 * @description 解决1.335.toFixed(2) // 1.33 错误
 * 保留几位小数
 * @param {*} val
 * @param {*} num
 * @returns
 */

export const keepDecimal = (val, num = 2) => {
  if (val === '--' || val === '' || val === null || val == undefined) {
    return '--';
  }
  if (Object.prototype.toString.call(val) == '[object String]') {
    let val_new = parseFloat(val);
    if (isNaN(val_new)) {
      return val;
    } else {
      try {
        return (Math.round(val_new * 100) / 100).toFixed(num);
        // val_new.toFixed(num)
      } catch (error) {
        console.error(error);
        return val;
      }
    }
  }

  if (isNaN(val)) {
    return val;
  } else {
    try {
      return (Math.round(val * 100) / 100).toFixed(num);
      // val_new.toFixed(num)
    } catch (error) {
      console.error(error);
      return val;
    }
  }
};

export const toVal = (obj, ...args) => {
  const val = getVal(obj, ...args);
  return val === null ? '--' : val;
};
/**
 * 判断父元素有没有子元素
 * @param {*} parent
 * @param {*} child
 * @returns  true || false
 */
export const elementContains = (parent, child) =>
  parent !== child && parent.contains(child);

/**
 * @description: 去除字符串中的数字
 * @param {String}
 * @return {*}
 */
export const strRemoveNum = (str) => {
  return str.replace(/[0-9]+/g, '');
};

// 下载文件
export function downExceil(option) {
  const {
    url,
    name = 'exceil',
    query,
    type = 'xls',
    method = 'get',
    data = {},
  } = option;
  if (method == 'get') {
    var xhr = new XMLHttpRequest(); //定义http请求对象
    xhr.open('get', url, true);
    // xhr.setRequestHeader('x-access-token', headersTmp['x-access-token'])
    xhr.send();
    xhr.responseType = 'blob'; // 返回类型blob
    xhr.onload = function () {
      // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
      if (this.status === 200) {
        var blob = this.response;
        let contentDisposition = xhr.getResponseHeader('content-disposition');
        let temp = contentDisposition
          ? xhr
              .getResponseHeader('content-disposition')
              .split(';')[1]
              .split('filename=')[1]
          : '';

        var reader = new FileReader();
        reader.readAsDataURL(blob); // 转换为base64,可以直接放入a标签href
        reader.onload = function (e) {
          console.log(e); //查看有没有接收到数据流
          // 转换完成,创建一个a标签用于下载
          const elink = document.createElement('a');
          // iso8859-1 转为utf-8
          // elink.download = decodeURI(escape(temp)) + '.' + type
          elink.download = decodeURI(escape(temp));
          elink.style.display = 'none';

          elink.href = e.target.result;
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        };
      }
    };
  } else {
    console.log(query, 'post');

    axios
      .post(url, query, {
        responseType: 'blob',
        params: query,
      })
      .then((res) => {
        // console.log('下载数据', res)
        const blob = new Blob([res.data]); //处理文档流
        const fileName = res.headers['content-disposition'];
        const elink = document.createElement('a');
        elink.download = decodeURI(
          escape(fileName.split(';')[1].split('filename=')[1])
        );
        // elink.download = decodeURI(fileName.split('filename=')[1])
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      });
  }
}

/**
 * @description: 对象、数组深拷贝
 * @param {Object、Array}
 * @return {*}
 */
export const objDeepCopy = (obj) => {
  var result = Array.isArray(obj) ? [] : {};
  // 判断传入拷贝对象是否数组,是创建新数组[],否则创建新对象{}
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      // 判断对象是否包含特定的自身(非继承)属性。
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        // typeof 对象 | 数组 | null ,返回 'object'
        result[key] = objDeepCopy(obj[key]); //递归复制
      } else {
        result[key] = obj[key];
      }
    }
  }
  return result;
};

/**
 * @description: 判断两个对象是否相等
 * @param {Object、Object}
 * @return {*}
 */
export const isEqual = (objA, objB) => {
  //相等
  if (objA === objB) return objA !== 0 || 1 / objA === 1 / objB;
  //空判断
  if (objA == null || objB == null) return objA === objB;
  //类型判断
  if (
    Object.prototype.toString.call(objA) !==
    Object.prototype.toString.call(objB)
  )
    return false;

  switch (Object.prototype.toString.call(objA)) {
    case '[object RegExp]':
    case '[object String]':
      //字符串转换比较
      return '' + objA === '' + objB;
    case '[object Number]':
      //数字转换比较,判断是否为NaN
      if (+objA !== +objA) {
        return +objB !== +objB;
      }

      return +objA === 0 ? 1 / +objA === 1 / objB : +objA === +objB;
    case '[object Date]':
    case '[object Boolean]':
      return +objA === +objB;
    case '[object Array]':
      //判断数组
      for (let i = 0; i < objA.length; i++) {
        if (!isEqual(objA[i], objB[i])) return false;
      }
      return true;
    case '[object Object]': {
      let keys = Object.keys(objA);
      for (let i = 0; i < keys.length; i++) {
        if (!isEqual(objA[keys[i]], objB[keys[i]])) return false;
      }

      keys = Object.keys(objB);
      for (let i = 0; i < keys.length; i++) {
        if (!isEqual(objA[keys[i]], objB[keys[i]])) return false;
      }
      return true;
    }
    //判断对象

    default:
      return false;
  }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值