Vue.jsでカウントダウン機能を実装する

Vue.js でカウントダウン機能を実装する JavaScript
記事内に広告が含まれています。

この記事では、Vue.jsを使ってカウントダウン機能を実装する方法について書いています。

カウントダウンに関しては、様々なライブラリがあるかと思いますが、今回はそういったものは使用せずに実装しました。

Vue.jsでカウントダウン機能を実装する

Countdown.vueファイルを作成

カウントダウン用のコンポーネントファイルを作成。今回は以下のように実装します。

  • 指定日を2021年10月01日12時に
  • 2021年09月30日23時59分59秒までは日数を表示
  • 2021年10月01日0時からはHH時間MM分SS秒で表示
  • 2021年10月01日12時以降は、「カウントダウンが終了しました」と表示

Countdown.vue

<template>
  <div id="countdown">
    <div class="countdown-wrapper">
      <div class="countdown-date" v-if="diffDays > 0">
        <p>カウントダウン終了まで、あと{{ diffDays }}日</p>
      </div>
      <div class="countdown-time" v-else-if="diffDays <= 0 && this.diff > 0">
        <p>
          カウントダウン終了まで、あと
          {{ ('0' + this.countdownTimer.hours).slice(-2) }}時間{{ ('0' + this.countdownTimer.minutes).slice(-2) }}分{{ ('0' + this.countdownTimer.seconds).slice(-2) }}秒
        </p>
      </div>
      <div class="countdown-end" v-else-if="this.diff < 0">
        <p>カウントダウンは終了しました</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Countdown",
  props: {
    unixtime: {
      type: Number
    }
  },
  data() {
    return {
      range: 43200,
      timerObject: null,
      diff: null,
      countdownTimer: {
        hours: 0,
        minutes: 0,
        seconds: 0
      }
    }
  },
  created() {
    const tDate = new Date(parseInt(this.unixtime * 1000, 10)); // unixtimeは親コンポーネントで指定した1633057200が渡ってくる。Dateがミリ秒数なので*1000を行う。parseIntの第二引数には10進数を指定
    const nDate = new Date(); // 現在時刻を取得
    this.diff = tDate.getTime() - nDate.getTime(); // 指定した時刻 - 現在時刻。getTime()は経過ミリ秒数を返す
    this.tick(this); // -1秒ずつ。this=windowオブジェクト
  },
  mounted() {
    const self = this;
    this.timerObject = setInterval(function () { // 1秒ごとに-1秒ずつ
      self.tick(self);
    }, 1000);
  },
  computed: {
    diffDays() { // 残り日数
      const rangeDate = new Date(parseInt(this.range * 1000, 10)); // Thu Jan 01 1970 21:00:00 GMT+0900 (日本標準時)
      return (Math.floor((this.diff + rangeDate.getTime()) / 1000 / 24 / 3600));
    },
  },
  methods: {
    tick: function (self) {
      self.diff = self.diff - 1000; // -1秒ずつ
      self.countdownTimer.hours = Math.floor(self.diff / 1000 / 3600);
      self.countdownTimer.minutes = Math.floor((self.diff - (self.countdownTimer.hours * 1000 * 3600)) / 1000 / 60);
      self.countdownTimer.seconds = Math.floor((self.diff - (self.countdownTimer.hours * 1000 * 3600) - (self.countdownTimer.minutes * 1000 * 60)) / 1000);
    }
  }
}
</script>

index.vueファイルでCountdownコンポーネントを表示

index.vue

<template>
  <!-- unixtime:1633057200 = 2021年10月01日12時を指定 -->
  <countdown :unixtime="1633057200"></countdown>
</template>

<script>
import Countdown from "../components/Countdown";

export default {
  components: {
    Countdown
  }
}
</script>
Vue.js関連のおすすめ書籍

コメント

タイトルとURLをコピーしました