js獲取當前時間並實時刷新1


顯示代碼

{{$moment(nowTime).format("YYYY-MM-DD HH:mm:ss")}} {{nowWeek}}

 data() {
    return {
      nowTime: new Date(),
      weekDays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
      timer: null
    };
  },
  mounted() {
    // 初始化時間
    this.init();
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  computed: {
    nowWeek() {
      return (this.nowTime && this.weekDays[this.nowTime.getDay()]) || "";
    }
  },
  methods: {
    init() {
      this.startTimer();
    },
    // 啟動定時器,定時刷新時間
    startTimer() {
      this.nowTime = new Date();
      setTimeout(() => {
        this.nowTime = new Date();
        this.timer = setInterval(() => {
          this.nowTime = new Date();
        }, 1000);
      }, 1000 - this.nowTime.getMilliseconds());
    }
  }


免責聲明!

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



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