スマレジエンジニアyushiのブログ

スマレジエンジニアのブログ

【タイマー 第1回】タイマーアプリを作ってみる

最近のマイブームで、ルービックキューブにはまっています。

パズルとして解くのではなく、手順を覚えてタイムアタックする感じです。

せっかくなので、自分でストップウォッチを作って、それで時間計測できるようにしたいと思います。

技術要素

今回もVue.js3を使います。

  • Vue.js3
  • Vite

プロジェクト作成

手順はこちらの通りです。

Installation | Vue.js

$ create-vite-app <project-name>

簡単なタイマー機能

ロジック

ひとまず、スタート〜ストップのみのストップウォッチ機能を作ってみます。

Composition APIでロジックを記述します。

export default function useTimer() {
  // data
  const count = ref(0)
  const startTime = ref(0)
  const intervalId = ref(0)
  const timerTime = ref(0)

  // computed
  const viewTimerTime = computed(() => (timerTime.value / 1000).toFixed(1))
  const isRunning = computed(() => !!intervalId.value)

  // methods
  const startTimer = () => {
    intervalId.value = setInterval(() => {
      timerTime.value = (Date.now() - startTime.value)
    }, 10)
  }
  const start = () => {
    startTime.value = Date.now()
    startTimer()
  }
  const stop = () => {
    clearInterval(intervalId.value)
    intervalId.value = 0
  }

  return {
    count,
    startTime,
    timerTime,
    viewTimerTime,
    isRunning,
    start,
    stop,
  }
}

まずはスタートとストップをするだけです。

画面

画面はもちろん、Vue.jsで書きます。

<template>
  <div>
    <h1>Timer</h1>
    <p>{{ viewTimerTime }}</p>
    <button @click="start" :disabled="isRunning">Start</button>
    <button @click="stop" :disabled="!isRunning">Stop</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import useTimer from '../composable/use-timer'

export default defineComponent({
  name: 'Timer',
  props: {
    msg: {
      type: String,
      required: true
    }
  },
  setup: () => {
    const timer = useTimer()

    return {
      ...timer,
    }
  }
})
</script>

完成した画面

f:id:yushi0:20210613221335p:plain

PR

  • プロジェクト作成

Create vite app by nek0meshi · Pull Request #1 · nek0meshi/timer · GitHub

  • タイマーの機能

簡単なタイマー機能の実装 by nek0meshi · Pull Request #2 · nek0meshi/timer · GitHub

まとめ

今回は最低限の機能で実装しました。ここから機能拡張をしていきたいと思います。

将棋盤ではとりあえずバリバリロジックを書いていきましたが、今回はComposition APIを使いこなすところに主眼を置きたいと思っています。