vue-全局过滤器(时间,年月日,一千加逗号处理)

步骤一:处理数据 

export const formatYmd = (date) => {
  let time = new Date(date)

  let y = time.getFullYear()
  let m = time.getMonth() + 1
  let d = time.getDate()

  return [y, m, d].map((v) => String(v).padStart(2, '0')).join('/')
}

//处理年月日时分秒
export const formatYmdHms = (date) => {
  let time = new Date(date)

  let y = time.getFullYear()
  let M = time.getMonth() + 1
  let d = time.getDate()

  let h = time.getHours()
  let m = time.getMinutes()
  let s = time.getSeconds()

  return (
    [y, M, d].map((v) => String(v).padStart(2, '0')).join('-') +
    ' ' +
    [h, m, s].map((v) => String(v).padStart(2, '0')).join(':')
  )
}

//处理时分秒
export const formatHms = (date) => {
  let time = new Date(date)

  let h = time.getHours()
  let m = time.getMinutes()
  let s = time.getSeconds()

  return [h, m, s].map((v) => String(v).padStart(2, '0')).join(':')
}

//一千加逗号
export const formatNum = (num) => {
  let reg = /\d{1,3}(?=(\d{3})+$)/g
  // 表示前面有1~3个数字,后面的至少由一组3个数字结尾

  return (num + '').replace(reg, '$&,')

步骤二:main.js 注册全局过滤器

//引入过滤器函数
import * as filters from '@/filters'

//循环注册 全局过滤器
Object.keys(filters).forEach((key) => {
  //参数1 过滤器名称 参数2 过滤器函数体
  Vue.filter(key, filters[key])
})

步骤三:使用

{{ 234234 | formatNum}}

你可能感兴趣的:(vue.js,javascript,前端)