vue momentを使ってカウントアップの仕組みを作る

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます

<template>
  <p>{{ currentSpendTime }}</p>
</template>
<script>
  export default {
    data: function() {
      return {
        time : null,
        timer: null,
        currentSpendTime: "",
      }
    },
    methods: {
      // カウントアップスタート
      start(checklist) {
        this.time = new moment()
        let self = this; //setInterval内でこのComponentのmethodを指定するためにself変数を定義
        this.timer = setInterval(function() { self.currentTime() }, 1000)
      },
      // カウントアップストップ
      stop: function () {
        clearInterval(this.timer)
      },
      // momentを使って現在のカウントを currentSpendTime に保存する
      currentTime() {
        // ミリ秒からdurationオブジェクトを生成
        const duration = moment.duration( momentd().diff( this.time ) );
        // 日・時・分・秒を取得
        const hours   = duration.hours();
        const minutes = duration.minutes();
        const seconds = duration.seconds();
        this.currentSpendTime = `${hours}:${minutes}:${seconds}`
      },
...

</script>

Back