Vue全局注册过滤器

传统注册过滤器

1、先在 filters/index.js 文件中导出方法

/**
 *
 * @param {*} date
 * @returns
 */
export function dateTimeFormat(date) {
  const json_date = new Date(date).toJSON()
  console.log(json_date)
  return new Date(+new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

2、在 main.js 中导入方法并注册

import { dateTimeFormatData } from '@/filters' // 引入工具类
Vue.filter("dateTimeFormatData ", dateTimeFormatData )

3、在组件中使用过滤器

<el-table-column
  prop="timeOfEntry"
  label="入职时间"
  width="120"
>
  <template slot-scope="row">
    {{ row.row.timeOfEntry | dateTimeFormat }}
  </template>
</el-table-column>

缺点:main.js 中需要一个个导入方法并注册

使用全局方式导入所有的过滤器

1、在 filters/index.js 中导出方法

/**
 *
 * @param {*} date
 * @returns
 */
export function dateTimeFormat(date) {
  console.log(date)
  const json_date = new Date(date).toJSON()
  console.log(json_date)
  return new Date(+new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

/**
 *
 * @param {*} date
 * @returns
 */
export function dateTimeFormatData(date) {
  const d = new Date(date)
  return d.getFullYear() + '-' + (d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1) + '-' + (d.getDate() < 10 ? '0' + d.getDate() : d.getDate())
}

2、在 main.js 中统一注册过滤器

import * as filters from '@/filters' // 引入工具类

Object.keys(filters).forEach(key => {
  // 注册过滤器
  Vue.filter(key, filters[key])
})

3、在组件中使用过滤器

<el-table-column
  prop="timeOfEntry"
  label="入职时间"
  width="120"
>
  <template slot-scope="row">
    {{ row.row.timeOfEntry | dateTimeFormat }}
  </template>
</el-table-column>

<el-table-column
  prop="timeOfEntry"
  label="入职时间"
  width="120"
>
  <template slot-scope="row">
    {{ row.row.timeOfEntry | dateTimeFormat}}
  </template>
</el-table-column>

优点:一次性将 filters/index.js 中的方法导入,并使用循环注册过滤器

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值