js获取当前时间并实时刷新1
显示代码
{{$moment(nowTime).format("YYYY-MM-DD HH:mm:ss")}} {{nowWeek}}
data() {
return {
nowTime: new Date(),
weekDays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
timer: null
};
},
mounted() {
// 初始化时间
this.init();
},
destroyed() {
if (this.timer) {
clearInterval(this.timer);
}
},
computed: {
nowWeek() {
return (this.nowTime && this.weekDays[this.nowTime.getDay()]) || "";
}
},
methods: {
init() {
this.startTimer();
},
// 启动定时器,定时刷新时间
startTimer() {
this.nowTime = new Date();
setTimeout(() => {
this.nowTime = new Date();
this.timer = setInterval(() => {
this.nowTime = new Date();
}, 1000);
}, 1000 - this.nowTime.getMilliseconds());
}
}
择善人而交,择善书而读,择善言而听,择善行而从。