功能需求:獲取當前系統時間,在頁面上顯示:年月日時分秒,並且實時刷新,和系統時間保持一致
第一步:在deta 里面聲明變量
data() {
return {
nowDate:null, //存放年月日變量
nowTime:null, //存放時分秒變量
timer: "", //定義一個定時器的變量
currentTime: new Date(), // 獲取當前時間
}
},
第二步:定義獲取日期時間方法getTime,並在created() 生命周期里面調用,在實例創建前調用
created() {
this.timer = setInterval(this.getTime, 1000);
},
方法getTime如下:
methods: {
getTime(){
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour= date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const str = ''
if(this.hour>12) {
this.hour -= 12;
this.str = " AM";
}else{
this.str = " PM";
}
this.month=check(month);
this.day=check(day);
this.hour=check(hour);
this.minute=check(minute);
this.second=check(second);
function check(i){
const num = (i<10)?("0"+i) : i;
return num;
}
this.nowDate = year + "年" + this.month + "月" + this.day+"日";
this.nowTime = this.hour + ":" + this.minute + ":" + this.second + this.str;
},
}
第三步:離開頁面使用beforeDestroy() 銷毀
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer); // 在Vue實例銷毀前,清除定時器
}
},
第四步:在頁面需要顯示的地方綁定{{ nowDate }},{{ nowTime }}即可
