vue中實現時間格式化 dayjs插件


 

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);
    }
  }

實現效果  (時間隔一秒跳一次)

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM