一些方法的封装

91 阅读1分钟

导出excel文件的封装

/**
 * 导出excel文件
 * @param tableCols 表头
 * @param dataList  后台返回的数据
 * @param filename  导出的文件名
 * @param fileType  文件类型,默认为 xlsx,csv导出的长数据可能会被科学计数
 */
export const exportExcel = (tableCols: any, dataList: any, filename: string, fileType = 'xlsx') => {
  const excelData: any = [];
  const tHead: any = [];
  const dataLen = dataList.length;
  tableCols.forEach(({ value, label }: any, index: number) => {
    tHead.push(label);
    for (let i = 0; i < dataLen; i += 1) {
      if (!excelData[i]) excelData[i] = [];
      const data = dataList[i][value];
      excelData[i][index] = data.toString() || '-';
    }
  });
  excelData.unshift([...tHead]);
  const aoaToSheet = XLSX.utils.aoa_to_sheet(excelData);
  const bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, aoaToSheet);
  XLSX.writeFile(bookNew, `${filename}.${fileType}`);
};

时间戳的格式化

/**
 * 将秒级时间戳格式化
 * @param timestamp
 * @param format
 */
export const formatTimestamp = (timestamp: number, format = 'YYYY/MM/DD HH:mm:ss') => {
  if (timestamp) {
    if (String(timestamp).length === 10) {
      return dayjs(timestamp * 1000).format(format);
    }
    if (String(timestamp).length === 13) {
      return dayjs(timestamp).format(format);
    }
  }
  return '';
};

判断url的有效性

const validateURL = function (textval) {
  const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
  return urlregex.test(textval);
};

输入框不能含有表情字符

// 不能含有表情字符
const emojiReg = /^([\u0000-\u007F]|[\u4E00-\u9FCC\u3400-\u4DB5\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\ud840-\ud868]|[\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|[\ud86a-\ud86c][\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d])+$/;

// 不能含有表情字符
const emojiValidate = {
  pattern: emojiReg,
  message: '不能含有非法字符和表情',
};
// 在组件中的使用
<el-form-item
    prop="planningName"
    label="排期名称"
    :rules="[
        { required: true, message: '请输入排期名称' },
        emojiValidate
    ]"
>
</el-form-item>
// 或是
rules: {
    planningName: [
        { required: true, message: '请输入排期名称', trigger: 'blur' },
        emojiValidate,
]}

对象和数组之间的转换

const accountTypeOptions = [{
  label: '23',
  value: 1,
}, {
  label: '34',
  value: 2,
}, {
  label: '56',
  value: 3,
}, {
  label: '546',
  value: 4,
}, {
  label: '567',
  value: 5,
}];
const accountTypeMap = Object.fromEntries(accountTypeOptions.map(({ label, value }) => [value, label]));

价格进行格式化

const formatPrice = (coin) => {
  // 如果是整数,则不显示小数位
  if (+parseFloat(`${coin / 100}`).toFixed(2) === Math.floor(coin / 100)) {
    return `${Math.floor(coin / 100)}`;
  }
  return parseFloat(`${coin / 100}`).toFixed(2)
    .toLocaleString();
};

文件下载

// 写入txt文件 并放入上传的文件列表中
const txt = qqList.map(item => `${item}\n`);
const fileName = `${dayjs().format('YYYY-MM-DD')}-${songName}.txt`;
const file = new File(txt, fileName, { type: 'text/plain' });
this.fileListTxt = [file];
// 点击文件 下载到本地
onFilePreview(file) {
    const url = URL.createObjectURL(file);
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', file.name);
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(url);
    document.body.removeChild(link);
}