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