每秒请求一次当前时间
<li class="time">{{nowTime}}</li>
data() {
return {
nowTime: new Date()
}
},
mounted: function () {
this.timer = setInterval(() => {
this.nowTime = dateFormat(new Date())
}, 1000)
}
销毁的时候清除定时器
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer);
}
},
dateFormat方法
export const dateFormat = (date) => {
var year = date.getFullYear();
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
let week = date.getDay(); // 星期
let weekArr = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",];
return (year + "年" + month + "月" + day + "日 " + hours + ":" + minutes + ":" + seconds + " " + weekArr[week]);
}
该文章展示了如何在Vue.js应用中每秒获取并显示当前时间,使用定时器设置回调函数更新时间,并进行日期格式化处理。在组件销毁时,确保正确清理定时器以避免内存泄漏。

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



