1、模板内容
<div>{{ nowTime }}</div>
2.data数据
timer: "", //定义一个定时器
nowTime: "", // 当前日期时间
3.methods获取当前时间日期
getTime() {
this.timer = setInterval(() => {
let timeDate = new Date();
let year = timeDate.getFullYear();
let mounth = timeDate.getMonth() + 1;
let day = timeDate.getDate();
let hours = timeDate.getHours();
hours = hours >= 10 ? hours : "0" + hours;
let minutes = timeDate.getMinutes();
minutes = minutes >= 10 ? minutes : "0" + minutes;
let seconds = timeDate.getSeconds();
seconds = seconds >= 10 ? seconds : "0" + seconds;
let week = timeDate.getDay();
let weekArr = [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六",
];
this.nowTime = `${year}-${mounth}-${day} ${hours}:${minutes}:${seconds} ${weekArr[week]}`;
}, 1000);
},
4、mounted里调用时间日期方法
this.getTime();
5、页面关闭销毁定时器
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer);
}
},