使用setInterval定时器实现
data(){
return {
time: '',
}
}
mounted(){
this.displayDateTime()
}
methods: {
displayDateTime() {
setInterval(() => {
var now = new Date();
// 获取年月日
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
// 获取小时分钟秒数
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// 格式化为双位数
month = ("0" + month).slice(-2);
day = ("0" + day).slice(-2);
hours = ("0" + hours).slice(-2);
minutes = ("0" + minutes).slice(-2);
seconds = ("0" + seconds).slice(-2);
this.time = year + "-" + month + "-" + day + "-" + hours + ":" + minutes + ":" + seconds;
},1000)//每秒更新一次
}
}