Vueでカウントアップ
これを参考にした
https://gyazo.com/c9d2f4176b1b01d966105ae054a458e2
CoutUpTimer.vue
code:CountUpTimer.js
<template>
<div>
<p>{{ displayCountUpTimer }}</p>
</div>
</template>
<script>
import displayCountUpTimer from '~/utils/countUp'
export default {
data() {
return {
countUpTimerIntervalId: undefined,
seconds: 0
}
},
computed: {
displayCountUpTimer() {
return displayCountUpTimer(this.seconds)
}
},
mounted() {
const that = this
this.countUpTimerIntervalId = setInterval(function() {
that.countUp()
}, 1000)
},
beforeDestroy() {
clearInterval(this.countUpTimerIntervalId)
},
methods: {
countUp() {
this.seconds++
}
}
}
</script>
code:displayCountUpTimer.js
export default function(seconds) {
const padZero = (number) => {
const str = String(number)
return str.length < 2 ? '0' + str : str
}
const hour = Math.floor(seconds / (60 * 60))
const min = Math.floor(seconds / 60) % 60
const second = seconds % 60
return hour > 0
? ${hour}:${padZero(min)}:${padZero(second)}
: ${min}:${padZero(second)}
}
------
aleart追加版
CountUpTimer.vue
code:CountUpTimer.js
<template>
<div>
<p>{{ displayCountUpTimer }}</p>
<button @click="handleCancel">キャンセル</button>
</div>
</template>
<script>
import displayCountUpTimer from '~/utils/displayCountUpTimer'
export default {
data() {
return {
countUpTimerIntervalId: undefined,
alertTimeoutId: undefined,
seconds: 0
}
},
computed: {
displayCountUpTimer() {
return displayCountUpTimer(this.seconds)
}
},
mounted() {
const that = this
this.countUpTimerIntervalId = setInterval(function() {
that.countUp()
}, 1000)
this.alertTimeoutId = setTimeout(function() {
alert('あああ')
}, 5500)
},
beforeDestroy() {
clearInterval(this.countUpTimerIntervalId)
clearTimeout(this.alertTimeoutId)
},
methods: {
handleCancel() {
clearTimeout(this.countUpTimerIntervalId)
clearTimeout(this.alertTimeoutId)
},
countUp() {
this.seconds++
}
}
}
</script>