跳到主要內容
前端開發

Vue 2 倒數計時器:套件與手刻兩種做法

記錄 2020 年使用 vue2-flip-countdown,或以 setInterval 手刻倒數計時器的方式。

W

這邊記錄兩種倒數計時器的做法。

使用 vue2-flip-countdown

這個套件有翻牌動畫效果:

npm i vue2-flip-countdown --save

套件頁面:vue2-flip-countdown

手刻倒數計時器

<template>
  <ul>
    <li><h3>{{ days }}</h3><span>Days</span></li>
    <li><h3>{{ hours }}</h3><span>Hours</span></li>
    <li><h3>{{ minutes }}</h3><span>Minutes</span></li>
    <li><h3>{{ seconds }}</h3><span>Seconds</span></li>
  </ul>
</template>

<script>
export default {
  name: "TimerCountdown",
  props: ["gettimer"],
  data() {
    return {
      minutes: 0,
      seconds: 0,
      hours: 0,
      days: 0,
    };
  },
  mounted() {
    this.timerCount(this.gettimer);
  },
  methods: {
    timerCount(timer) {
      const countDownDate = new Date(timer).getTime();

      setInterval(() => {
        const now = new Date().getTime();
        const distance = countDownDate - now;

        this.days = Math.floor(distance / (1000 * 60 * 60 * 24));
        this.hours = Math.floor(
          (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60),
        );
        this.minutes = Math.floor(
          (distance % (1000 * 60 * 60)) / (1000 * 60),
        );
        this.seconds = Math.floor((distance % (1000 * 60)) / 1000);
      }, 1000);
    },
  },
};
</script>

父層引用:

<CountDown :gettimer="timer" />

2026 年後記

這是 Vue 2 的舊寫法,而且原範例沒有保存與清除 setInterval,元件銷毀後計時器仍可能繼續執行。若沿用這段概念,應保存計時器 ID,並在元件卸載時呼叫 clearInterval()

分享這篇