JS常用业务函数

200 阅读2分钟

1.根据出生日期计算年龄

/**
 * 根据出生日期计算年龄
 * @param {string} birthDate 格式: YYYY-MM-DD
 * @return {number}
 */
export function calculateAge(birthDate) {
  let today = new Date()
  let birth = new Date(birthDate)

  let age = today.getFullYear() - birth.getFullYear()

  // 检查是否已经过了生日
  let monthDiff = today.getMonth() - birth.getMonth()

  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--
  }

  return age
},

2.日期格式化

/**
 * 日期格式化
 * @param {object} date 格式: new Date()
 * @param {string} format 格式1(默认): YYYY-MM-DD, 格式2: YYYY-MM-DD HH:mm:ss (参考: http://momentjs.cn/)
 * @returns 
 */
export function dateFormat(date, format = "YYYY-MM-DD") {
    if (!date) return date
    try {
        return moment(date).format(format)
    } catch (error) {
        console.error(error, "dateFormat error")
        return date
    }
}

3.自定义指令

/**
 * 权限指令 
 * @param {string} value 权限标识
 * 例:<div v-permission="'table_del'"></div>
 */
Vue.directive('permission', {
  inserted: function (el, binding) {
    const { value } = binding
    // 获取VueX中的 权限按钮列表
    const buttonList = store.state.user.permission

    if (value) {
      // some 遇到 return true 时 会结束遍历
      const hasPermission = buttonList.some(btnKey => btnKey === value)
      // 没有权限直接移除 dom元素
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`需要指定权限标识! 如:v-permission="'table_del'"`)
    }
  }
})

4.数据归类

const data = [
  {
    "status": 0,
    "code": 200,
    "phone": "18022923898",
    "content": null,
    "message": "发送成功",
    "sGuid": "e52b84b5-f603-4beb-beff-7af352a9ba8f",
    "projectName": "数据1",
    "auditPerson": "刘杰"
  },
  {
    "status": 0,
    "code": 500,
    "phone": "13560051578",
    "content": null,
    "message": "发送短信发生异常:URI is not absolute",
    "sGuid": "e52b84b5-f603-4beb-beff-7af352a9ba8f",
    "projectName": "数据1",
    "auditPerson": "鲍魁"
  },
  {
    "status": 0,
    "code": 500,
    "phone": "13560051578",
    "content": null,
    "message": "发送短信发生异常:URI is not absolute",
    "sGuid": "e52b84b5-f603-4beb-beff-7af352a9ba8f",
    "projectName": "数据2",
    "auditPerson": "鲍魁"
  }
  // ... 其他数据对象
];
// 创建一个空对象,用于存储分类后的数据 
const categorizedData = {} // 遍历数据数组 
data.forEach((item) => { 
    const projectName = item.projectName; 
    // 如果分类对象中存在该项目名的属性,则将当前数据添加到对应属性的数组中 
    if (categorizedData.hasOwnProperty(projectName)) {
        categorizedData[projectName].push(item)
    } 
    // 否则,创建一个新的属性,并将当前数据作为第一个元素放入数组中 
    else { 
        categorizedData[projectName] = [item]
    } 
})
console.log(categorizedData);

image.png

5.链式方程

arr = arr
  .filter(item => item.d !== 'd')
  .map(item => {
    if (item.c && item.c.length > 0) {
      item.c = 'c'
    }
    return item
  });

6.字典数据

filters: {
    stautsFilter(status) {
      const statusMap = {
        0: '草稿',
        1: '待审核',
        2: '已通过',
        3: '不通过'
      }
      return statusMap[status]
    }
  },

7.函数额外带参

:http-request="(data) => httpRequest(data, '123')"

8.显示本地图片src

<img width="100%" :src="dialogImageUrl" alt="">

this.dialogImageUrl = require('@/assets/demo.png')