返回

Vue 中的常用工具函数

前端

前言
在 Vue.js 项目开发过程中,经常会遇到一些重复性或通用性的任务,为了提高开发效率和代码的可维护性,我们可以定义一些工具函数来简化这些任务。

一、自定义聚焦指令
在某些情况下,我们需要在组件挂载后自动聚焦某个元素,可以使用自定义指令来实现。

  1. 方式一:mounted 周期,ref + querySelector
// 指令定义
Vue.directive('focus', {
  mounted(el, binding) {
    // 获取需要聚焦的元素
    const target = el.querySelector(binding.value)
    if (target) {
      // 将焦点设置到目标元素
      target.focus()
    }
  }
})
<!-- 使用指令 -->
<input v-focus=".input-field" />
  1. 方式二:nextTick + ref
// 指令定义
Vue.directive('focus', {
  mounted(el, binding) {
    this.nextTick(() => {
      // 获取需要聚焦的元素
      const target = this.$refs[binding.value]
      if (target) {
        // 将焦点设置到目标元素
        target.focus()
      }
    })
  }
})
<!-- 使用指令 -->
<input ref="inputField" v-focus="inputField" />

二、日期格式化工具

在 Vue.js 项目中,经常需要对日期进行格式化,我们可以定义一个工具函数来简化这个过程。

// 日期格式化工具
const dateFormat = (date, format) => {
  // 如果没有传入日期,则使用当前时间
  if (!date) {
    date = new Date()
  }
  // 如果没有传入格式,则使用默认格式
  if (!format) {
    format = 'yyyy-MM-dd hh:mm:ss'
  }
  // 填充占位符
  const padZero = (num) => {
    return num < 10 ? '0' + num : num
  }
  // 格式化日期
  const result = format.replace(/yyyy/g, date.getFullYear())
    .replace(/MM/g, padZero(date.getMonth() + 1))
    .replace(/dd/g, padZero(date.getDate()))
    .replace(/hh/g, padZero(date.getHours()))
    .replace(/mm/g, padZero(date.getMinutes()))
    .replace(/ss/g, padZero(date.getSeconds()))
  return result
}
<!-- 使用工具函数 -->
{{ dateFormat(new Date(), 'yyyy-MM-dd') }}

三、金额格式化工具

在 Vue.js 项目中,经常需要对金额进行格式化,我们可以定义一个工具函数来简化这个过程。

// 金额格式化工具
const moneyFormat = (value, currency = '¥') => {
  // 如果没有传入金额,则使用 0
  if (!value) {
    value = 0
  }
  // 如果没有传入货币符号,则使用默认符号 ¥
  if (!currency) {
    currency = '¥'
  }
  // 格式化金额
  const result = currency + value.toFixed(2)
  return result
}
<!-- 使用工具函数 -->
{{ moneyFormat(1234.56) }}

四、其他工具函数

除了上述工具函数,还可以根据项目的具体需求定义其他工具函数,例如:

  • 将数字转换为百分比
  • 将字符串转换为驼峰命名法
  • 将字符串转换为下划线命名法
  • 深拷贝对象
  • 判断对象是否为空
  • 延迟执行函数
  • 节流函数
  • 防抖函数

总结
以上是一些 Vue.js 中常用的工具函数,这些工具函数可以帮助我们简化和优化 Vue.js 开发,提高开发效率。当然,根据项目的具体需求,我们还可以定义更多实用的工具函数,从而使开发过程更加高效和愉悦。