vue全局filter

export function timestampFormatFilter(time, format) {
  if (!time) {
    return '无'
  }
  format = format || 'yyyy-MM-dd HH:mm:ss'
  const date = new Date(time)
  const map = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var key in map) {
    if (new RegExp(`(${key})`).test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? map[key] : numHelper(map[key]))
    }
  }
  return format
}

function numHelper(num) {
  if (num < 10) {
    return '0' + num
  } else {
    return num + ''
  }
}

在main.js 中设置

import * as filters from './filters' // global filters

Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

dom中就可以全局使用了
image.png

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