❤️⭐ 前端都需要知道的开发工具函数,都用得上,建议收藏 ⭐❤️

2022-06-16 11:40:28 浏览数 (3)

这里写目录标题
  • 一、格式化年月日 传法:`tool.parseTime(new Date(), "{y}-{m}")`
  • 二、首字母大小写
  • 三、获取当前月 `适用于elementUI及elementUI plus)`
  • 四、获取上月 `(适用于elementUI及elementUI plus)`
  • 五、获取当前周 `(适用于elementUI及elementUI plus)`
  • 六、当后端传回的数据不是数据流,此时想要导出Excel表格 可以使用这个
  • 七、那既然有后端返回不是数据流的方式 也会有返回数据流的方式,返回数据流相对要简单很多

一、格式化年月日 传法:tool.parseTime(new Date(), "{y}-{m}")

代码语言:javascript复制
// 日期格式化
tool.parseTime = function (time, pattern) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9] $/.test(time))) {
            time = parseInt(time)
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth()   1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a) }/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
            value = '0'   value
        }
        return value || 0
    })
    return time_str
}

二、首字母大小写

代码语言:javascript复制
// 首字母大小
tool.titleCase = function (str) {
    return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}
 
// 下划转驼峰
tool.camelCase = function (str) {
    return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

三、获取当前月 适用于elementUI及elementUI plus)

代码语言:javascript复制
// 获取月范围Date对像
tool.getMonthDateRange = function (oDate: Date) {
    let year = oDate.getFullYear()
    let month = oDate.getMonth()
    let start, end
    if (month == 0) {
        year--
        start = new Date(year, 0, 1)
        end = new Date(year, 12, 31)
    } else {
        start = new Date(year, month, 1)
        end = new Date(year, month   1, 0)
    }
    return [start, end]
}

四、获取上月 (适用于elementUI及elementUI plus)

代码语言:javascript复制
// 获取周范围Date对像
tool.getLastMonthDateRange = function (oDate: Date) {
    let year = oDate.getFullYear()
    let month = oDate.getMonth()
    let start, end
    if (month == 0) {
        year--
        start = new Date(year, 11, 1)
        end = new Date(year, 11, 31)
    } else {
        start = new Date(year, month - 1, 1)
        end = new Date(year, month, 0)
    }
    return [start, end]
}

五、获取当前周 (适用于elementUI及elementUI plus)

代码语言:javascript复制
// 获取周范围Date对象
tool.getWeekDateRange = function (oDate: Date) {
    const end = cloneDeep(oDate)
    const start = cloneDeep(oDate)
    const nows = start.getDay() || 7 // 周日算第一天,如果周日查询本周的话,天数是0,所有如     果是0,默认设置为7
    const endNows = 0 // 周日算第一天,如果周日查询本周的话,天数是0,所有如     果是0,默认设置为7
    start.setTime(start.getTime() - 3600 * 1000 * 24 * (nows - 1))
    end.setTime(end.getTime() - 3600 * 1000 * 24 * (nows - 7))
    return [start, end]
}

另外如果要在工具函数中使用vueX的数据的话,记得使用await处理异步问题,如:

代码语言:javascript复制
await store.dispatch("sys/user/set", userInfo)

六、当后端传回的数据不是数据流,此时想要导出Excel表格 可以使用这个

代码语言:javascript复制
//后端返回的数据是这样的
{
	"code":200,
	"data":{
		"dataList":[
			{
				"mealCount":2,
				"payMoney":1501,
				"subsidyMoney":1501,
				"uid":1,
				"userName":"张三"
			},
			{
				"mealCount":1,
				"payMoney":1,
				"subsidyMoney":1,
				"uid":136,
				"userName":"李四"
			},
			{
				"mealCount":1,
				"payMoney":1,
				"subsidyMoney":1,
				"uid":4,
				"userName":"王五"
			}
		]
	},
	"msg":"success"
}

那么这是相应的触发事件

代码语言:javascript复制
async onExportClick() {
        state.exportLoading = true;
        let res = await api.queryMealSubsidyMonth({
          subsidyMonth: subsidyMonth,
        });        
        // 定义表格标题
        let excelTitle = subsidyMonth;
        if (res.code == 200) {
          let tHeader: string[] = [];
          let filterVal: string[] = [];
          let columnList= [
            { colName: "用户ID", colFiled: "uid" },
            { colName: "姓名", colFiled: "userName" },
            { colName: "支付金额", colFiled: "payMoney" },
            { colName: "点餐数量", colFiled: "mealCount" },
            { colName: "补贴金额", colFiled: "subsidyMoney" },
          ],
          columnList.map((colItem: any) => {
            tHeader.push(colItem.colName);
            filterVal.push(colItem.colFiled);
          });
 
          let dataList: SubsidyItem[] = res.data.dataList;
          // 金额分转化为金额元
          dataList.map((subsidyItem: SubsidyItem) => {
            subsidyItem.payMoney = subsidyItem.payMoney / 100;
            subsidyItem.subsidyMoney = subsidyItem.subsidyMoney / 100;
          });
          const data = util.tool.formatJson(filterVal, dataList);
          let timestamp = new Date().valueOf();
 
          let fileName = `${excelTitle}的餐补信息`;
          console.log(tHeader, "tHeader");
          console.log(data, "data");
          util.excel.exportJson2Excel(
            tHeader,
            data,
            fileName,
            undefined,
            undefined
          );
          setTimeout(() => {
            state.exportLoading = false;
          }, 500);
        } else {
          ElMessage({
            message: res.data.message,
            type: "error",
            duration: 2 * 1000,
          });
          setTimeout(() => {
            state.exportLoading = false;
          }, 500);
        }
        setTimeout(() => {
          state.exportLoading = false;
        }, 5000);
        console.log("onExportClick");
      },

相应的工具函数:

代码语言:javascript复制
//处理Excel的行数据 一定要return出去 否则map无法导出
tool.formatJson = function (filterKeys: any, jsonData: any) {
    return jsonData.map((data: any) => filterKeys.map((key: string) => {
        if (key === 'timestamp') {
            return tool.parseTime(data[key])
        } else {
            return data[key]
        }
    }))
}
 
//导出Excel的主要函数
excel.exportJson2Excel = function (header: string[], data: any, filename = 'excel-list', multiHeader: string[][] = [], merges: any[] = [], autoWidth = true, bookType = 'xlsx') {
  data = [...data]
  data.unshift(header)
  for (let i = multiHeader.length - 1; i > -1; i--) {
    data.unshift(multiHeader[i])
  }
  
  const wsName = 'SheetJS'
  const wb = new Workbook()
  const ws = sheetFromDataArray(data)
 
  if (merges.length > 0) {
    if (!ws['!merges']) {
      ws['!merges'] = []
    }
    merges.forEach(item => {
      ws['!merges'].push(XLSX.utils.decode_range(item))
    })
  }
 
  if (autoWidth) {
    // 设置worksheet每列的最大宽度
    const colWidth = data.map((row: any) => row.map((val: any) => {
      // 先判断是否为 null/undefined
      if (val == null) {
        return {
          wch: 10
        }
        // 再判断是否为中文
      } else if (val.toString().charCodeAt(0) > 255) {
        return {
          wch: val.toString().length * 2
        }
      } else {
        return {
          wch: val.toString().length
        }
      }
    }))
    // 以第一行为初始值
    const result = colWidth[0]
    for (let i = 1; i < colWidth.length; i  ) {
      for (let j = 0; j < colWidth[i].length; j  ) {
        if (result[j].wch < colWidth[i][j].wch) {
          result[j].wch = colWidth[i][j].wch
        }
      }
    }
    ws['!cols'] = result
  }
 
  // Add worksheet to workbook
  wb.SheetNames.push(wsName)
  wb.Sheets[wsName] = ws
 
  const wbout = XLSX.write(wb, {
    bookType: bookType as any,
    bookSST: false,
    type: 'binary'
  })
 
  saveAs(new Blob([s2ab(wbout)], {
    type: 'application/octet-stream'
  }), `${filename}.${bookType}`)
}

七、那既然有后端返回不是数据流的方式 也会有返回数据流的方式,返回数据流相对要简单很多

那么这是相应的触发事件(因为是数据流就没CV后端数据上去)

代码语言:javascript复制
//导出Excel
async getExcel() {
        let res = await api.exportExcel(state.queryParams.salaryTemplateId)
        if (res.code == 500) {
          return false
        }
        const blob = new Blob([res])
        let link: any = document.createElement("a")
        link.href = URL.createObjectURL(blob)
        link.setAttribute("download", `${state.title}.xlsx`)
        link.click()
        link = null
},

0 人点赞