Vue项目中常用的函数合集

 1.excel导入功能

1.把excel文件中的日期格式的内容转回成标准时间

// 把excel文件中的日期格式的内容转回成标准时间
// https://blog.csdn.net/qq_15054679/article/details/107712966
export function formatExcelDate(numb, format = '/') {
  const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setYear(time.getFullYear())
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

 2.按接口要求,处理excel导入的数据

transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(zhObj => {
        const enObj = {}
        const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']

        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            // 后端需要的日期格式是标准时间
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })

        return enObj
      })
    },

 const data = this.transExcel(results)

2.平铺的数组转树形数据

function tranListToTreeData(arr) {
  const treeArr = []

  // 帮助快速确定上级
  const map = {}
  arr.forEach(item => {
    item.children = []
    map[item.id] = item
  })
  console.log(map)
  // 写代码
  arr.forEach(item => {
    // 对arr进行循环,对每一个元素item,如果
    // 1. item有上级元素pItem, 把item添加到pItem.children
    // 2. item没有上级元素(根据item.pid去找,找不到元素), 添加到treeArr
    const pItem = map[item.pid]
    if (pItem) {
      pItem.children.push(item)
    } else {
      treeArr.push(item)
    }
  })
  return treeArr
}

猜你喜欢

转载自blog.csdn.net/bukuaileya/article/details/128507056