本次案例使用局部过滤器
首先在需要显示时间的地方使用该过滤器:
<td>{{ time | filterTime('YYYY-MM-DD hh:mm:ss') }}</td>
// time 为使用 new Date() 获取的时间戳
// | 为管道符标识
// filterTime为过滤器名字 括号内传的参数为format的参数
// YYYY-MM-DD hh:mm:ss为日期的格式
然后,在Vue的组件中定义一个过滤器:
filters: {
// filterTime为过滤器名字
filterTime(data, format) {
// data 为管道符前面的数据 format 为传送的参数
// 获取年份
let year = data.getFullYear();
// 获取月份加一然后转为字符串,用 padStart方法补零
let months = (data.getMonth() + 1).toString().padStart(2, '0');
let days = data.getDate()
let hours = (data.getHours() + 1).toString().padStart(2, '0');
let minutes = (data.getMinutes() + 1).toString().padStart(2, '0');
let seconds = (data.getSeconds() + 1).toString().padStart(2, '0');
// 将传入的参数替换为获取的日期,链式调用,最后返回
return format.replace('YYYY', year).replace('MM', months).replace('DD', days).replace('hh', hours).replace('mm', minutes).replace('ss', seconds);
}
}
最后效果为