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 中的方法导入,并使用循环注册过滤器

posted @   DeyouKong  阅读(695)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-03-18 Echarts通过Ajax异步加载数据
点击右上角即可分享
微信分享提示