Vue.jsでカウントアップするタイマーのコンポーネントをつくった
必要に駆られて夜な夜な急遽作ったのですがせっかくなので置いておきます。
props
でタイマーのON/OFFをセットするよ。
<!-- Usage --> <CountUpTimer :on-start="isStarted" />
<template> <div class="count-up-timer"> <div class="time"> {{ time }} </div> </div> </template> <script> export default { name: 'CountUpTimer', props: { onStart: { type: Boolean, required: true, default: false } }, data() { return { totalSec: 0, timeKeeper: null } }, computed: { time() { const hour = Math.floor(this.totalSec / 3600) const min = Math.floor((this.totalSec - hour * 3600) / 60) const sec = this.totalSec % 60 const time = [] if (hour > 0) time.push(`0${hour}`) time.push(`00${min}`.slice(-2)) time.push(`00${sec}`.slice(-2)) return time.join(':') } }, watch: { onStart(started) { started ? this.start() : this.stop() } }, methods: { start() { this.timeKeeper = setInterval(() => { this.totalSec++ }, 1000) }, stop() { clearInterval(this.timeKeeper) } } } </script>