data 中创建变量:
timer: "",//定义一个定时器的变量
currentTime: new Date(), // 获取当前时间
1 created (){ 2 var _this = this; //声明一个变量指向Vue实例this,保证作用域一致 3 this.timer = setInterval(function() { 4 _this.currentTime = //修改数据date(改成指定的年月日时分秒格式) 5 new Date().getFullYear() + 6 "年" + 7 (new Date().getMonth() + 1) + 8 "月" + 9 new Date().getDate() + 10 "日 " + 11 new Date().getHours() + 12 "时" + 13 new Date().getMinutes() + 14 "分" + 15 new Date().getSeconds() + '秒'; 16 }, 0); 17 },
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer); // 在Vue实例销毁前,避免vipUpdate事件的多次触发 清除我们的定时器
}
}
放在created 中,确保页面一刷新前页面就可以获取