

1.項目中將dayjs寫成組件(common.js => 在common.js內引入 import dayjs from "dayjs";)


2.使用頁面 app.vue
引入common.js; import { parseDate2Str } from "@/util/common.js";
nowDate初始值取當前時間,並格式化; nowDate: parseDate2Str(new Date(), "YYYY-MM-DD HH:mm:ss");
使用定時器,隔一秒取一次;然后實例銷毀前,清除定時器;


3.相關少許代碼,貼碼
common.js內組件的時間及格式化
export function parseDate2Str(date, format) {
format = format || "YYYY-MM-DD HH:mm:ss";
return dayjs(date).format(format);
}
app.vue內定時器及清除定時器代碼
created() {
//定時器:獲取本地時間
this.timer = setInterval(() => {
this.nowDate =parseDate2Str(new Date(), "YYYY-MM-DD HH:mm:ss")
}, 1000);
},
beforeDestroy() {
//在vue實例銷毀前,清除定時器
if (this.timer) {
clearInterval(this.timer);
}
}
實現效果 (時間隔一秒跳一次)

