採用定時器來獲取最新的時間,通過Date的方法獲取年份、月份、日期、星期以及當前時間,用來拼裝時鐘,然後使用生命週期函數create來創建定時器,是時鐘每隔一秒鐘發生一次變化,達到時鐘在走的效果,同時在beforeDestroy函數中清除定時器
toTimeString() 方法可把 Date 對象的時間部分轉換爲字符串,並返回結果。
const days = ['天', '一', '二', '三', '四', '五', '六']; // 星期數組
let icnow = new Date(); // 初始化時間
let interval; // 定義全局定時器,用於清除定時器
export default {
name: 'app',
data() {
return {
year: icnow.getFullYear(),
month: icnow.getMonth() + 1,
date: icnow.getDate(),
day: days[icnow.getDay() - 1],
time: icnow.toTimeString().substring(0, 8)
}
},
created () {
interval = setInterval(() =>{
let icnow = new Date();
this.year = icnow.getFullYear();
this.month = icnow.getMonth() + 1;
this.date = icnow.getDate();
this.day = days[icnow.getDay()];
this.time = icnow.toTimeString().substring(0, 8);
}, 1000)
},
computed: {
// 當前時間
newTime: function () {
return this.year + '年' + this.month + '月' + this.date + '日 星期' + this.day + ' ' + this.time;
}
},
beforeDestroy () {
clearInterval(interval);
}
}