LoginSignup
3
2

More than 3 years have passed since last update.

[vue.js] ストップウォッチのコンポーネントを自作

Last updated at Posted at 2020-10-18

ストップウォッチをvue.jsコンポーネントで実装してみました。
自作のブラウザゲームでクリア時間を計るのに使ってます。

実行画面

image.png
時間は小数2桁まで表示。
Start/Stop ボタンと Reset ボタンを表示、ラップの記録機能は無し。

ソースコード

stopWatch.vue
<template>
<div>
    <p>{{interval.toFixed(2)}}</p> <!-- 小数2桁まで表示 -->
    <button @click="startTimer()" v-show="!active">Start</button>
    <button @click="stopTimer()" v-show="active">Stop</button>
    <button @click="resetTimer()">Reset</button>
</div>
</template>

<script>
export default {
    name: 'stopWatch',
    data(){
        return {
            active : false, // 実行状態
            start : 0, // startを押した時刻
            timer : 0, // setInterval()の格納用
            interval : 0, // 計測時間
            accum : 0, // 累積時間(stopしたとき用)
        }
    },
    methods:{
        startTimer(){
            this.active = true;
            this.start = Date.now();
            this.timer = setInterval(()=>{ this.interval = this.accum + (Date.now() - this.start) * 0.001;}, 10); // 10msごとに現在時刻とstartを押した時刻の差を足す
         },
        stopTimer(){
            this.active = false;
            this.accum = this.interval;
            clearInterval(this.timer);
        },
        resetTimer(){
            this.interval = 0;
            this.accum = 0;
            this.start = Date.now();
        }
    }
}
</script>
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2