需求:獲取當前系統時間,在頁面上展示 年月日 時分秒 ,並且實時刷新,和系統時間保持一致
第一步:在deta 里面聲明兩個變量
第二步:把時間調用寫在created() 生命周期里面,進入頁面就需要調用
第三步:離開頁面使用beforeDestroy() 銷毀
如下:
data() {
return {
timer: "",//定義一個定時器的變量
currentTime: new Date(), // 獲取當前時間
};
},
created() {
var _this = this; //聲明一個變量指向Vue實例this,保證作用域一致
this.timer = setInterval(function() {
_this.currentTime = //修改數據date
new Date().getFullYear() +
"-" +
(new Date().getMonth() + 1) +
"-" +
new Date().getDate() +
" " +
new Date().getHours() +
":" +
new Date().getMinutes() +
": " +
new Date().getSeconds();
}, 1000);
},
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer); // 在Vue實例銷毀前,清除我們的定時器
}
}
這樣就能滿足需求了 拿到的時間格式是 2019-8-16 8:9: 5
小於10的沒有加 0
如果需要的話可以使用下面的方法加上就可以了
//過濾加0
appendZero(obj) {
if (obj < 10) {
return "0" + obj;
} else {
return obj;
}
},