一、使用步骤
1.从服务器获取到时间戳并过滤
代码如下(示例):
<span>{{item.created|showDate}}</span>
2.在vue过滤器内编写showDate
代码如下(示例):
filters: {
showDate(value) {
//1.将时间戳转成Date实例对象
const date = new Date(value * 1000)
//2.把date传入封装好的formatDate函数进行时间格式化
return formatDate(date,'yyyy-MM-dd hh:mm:ss')
}
},
3.在使用组件内导入formatDate对象
import {formatDate} from "common/utils";
4.utils.js内编写formatDate函数
export function formatDate(date, fmt) {
//1.获取年份
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
//2.获取月,日,时,分,秒
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(RegExp.$1,(RegExp.$1.length === 1) ? str : padLeftZero(str));
}
}
return fmt;
}
//定义padLeftZero函数的返回值格式00:00:00
function padLeftZero(str) {
return ('00' + str).substr(str.length);
}
总结:
(1)格式转换没啥好说,看不懂就CV吧
(2)这里用到filters过滤器,我仔细思考了下为什么不用computed,发现二者还是很大不同的,要用cmoputed就先要拿到属性,如果这个属性是遍历出来就很麻烦。而filters是直接把item.created作为参数塞入showDate()中,不仅方便还有很强的复用性
本文介绍了在Vue中如何对时间戳进行格式化的步骤,包括从服务器获取时间戳后使用自定义过滤器`showDate`进行处理,以及在组件中引入`formatDate`函数的方法。强调了使用过滤器相比计算属性的便利性和复用性。
1178

被折叠的 条评论
为什么被折叠?



