Vue 中使用filters过滤器转列表时间格式
业务场景
当后端返回的列表每项的时间是这种 2023-11-16 14:22:50 , 业务需求需要的是 2023-11-16
1.封装公共方法 ( plugins/filters.js)
/**
* 时间格式化
* @param {*} dateStr 时间字符串
* @param {*} fmt 格式化类型
* @returns
*/
export const dateFormat = (dateStr, fmt = 'yyyy-MM-dd') => {
if(!dateStr)return '--';
let ret
const date = new Date(dateStr)
const opt = {
'y+': date.getFullYear().toString(), // 年
'M+': (date.getMonth() + 1).toString(), // 月
'd+': date.getDate().toString(), // 日
'H+': date.getHours().toString(), // 时
'm+': date.getMinutes().toString(), // 分
's+': date.getSeconds().toString(), // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
}
for (let k in opt) {
ret = new RegExp('(' + k + ')').exec(fmt)
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
)
}
}
return fmt
}
2.业务中使用
import { dateFormat } from "@/plugins/filters";
export default {
filters: {
dateFormat,
},
....
}
// 业务代码
<span class="org_time">
发布时间: {{ detailDatas.gmtCreate | dateFormat }}
</span>
// 当detailDatas.gmtCreate的值变化的时候就会执行 dateFormat 方法