HTML中的代码:
代码块:
{{timer | formatTimer}}
data中创建日期对象 :
加filters过滤,与created平齐:
代码块:
filters: {
formatTimer: function(value) {
let date = new Date(value);
let y = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? "0" + MM : MM;
let d = date.getDate();
d = d < 10 ? "0" + d : d;
let h = date.getHours();
h = h < 10 ? "0" + h : h;
let m = date.getMinutes();
m = m < 10 ? "0" + m : m;
let s = date.getSeconds();
s = s < 10 ? "0" + s : s;
return y + "-" + MM + "-" + d + " " + h + ":" + m;
}
},
加上mounted与beforeDestroy,代码块:
mounted() {
let _this = this; // 声明一个变量指向Vue实例this,保证作用域一致
this.timer1 = setInterval(() => {
_this.timer = new Date(); // 修改数据date
}, 1000)
},
beforeDestroy() {
if (this.timer1) {
clearInterval(this.timer1); // 在Vue实例销毁前,清除我们的定时器
}
},