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 中的方法导入,并使用循环注册过滤器
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2021-03-18 Echarts通过Ajax异步加载数据