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 中,確保頁面一刷新前頁面就可以獲取