vue实现正计时
实现正计时的基本思路
在Vue中实现正计时功能,可以通过以下方法完成。正计时通常从0开始,每秒递增,显示经过的时间。
使用data属性存储计时器状态
在Vue组件的data中定义计时器的初始值和计时器实例:
data() {
return {
seconds: 0,
timer: null
}
}
启动计时器的方法
在methods中定义startTimer方法,使用setInterval实现每秒更新:

methods: {
startTimer() {
this.timer = setInterval(() => {
this.seconds++
}, 1000)
}
}
停止计时器的方法
添加stopTimer方法清除计时器:
methods: {
stopTimer() {
clearInterval(this.timer)
this.timer = null
}
}
格式化显示时间
添加计算属性将秒数转换为更友好的格式(HH:MM:SS):

computed: {
formattedTime() {
const hours = Math.floor(this.seconds / 3600)
const minutes = Math.floor((this.seconds % 3600) / 60)
const secs = this.seconds % 60
return [
hours.toString().padStart(2, '0'),
minutes.toString().padStart(2, '0'),
secs.toString().padStart(2, '0')
].join(':')
}
}
组件生命周期管理
在组件销毁时自动清除计时器:
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer)
}
}
完整组件示例
<template>
<div>
<div>{{ formattedTime }}</div>
<button @click="startTimer" :disabled="timer">Start</button>
<button @click="stopTimer" :disabled="!timer">Stop</button>
</div>
</template>
<script>
export default {
data() {
return {
seconds: 0,
timer: null
}
},
computed: {
formattedTime() {
const hours = Math.floor(this.seconds / 3600)
const minutes = Math.floor((this.seconds % 3600) / 60)
const secs = this.seconds % 60
return [
hours.toString().padStart(2, '0'),
minutes.toString().padStart(2, '0'),
secs.toString().padStart(2, '0')
].join(':')
}
},
methods: {
startTimer() {
this.timer = setInterval(() => {
this.seconds++
}, 1000)
},
stopTimer() {
clearInterval(this.timer)
this.timer = null
}
},
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer)
}
}
}
</script>
使用Composition API的实现
对于Vue 3,可以使用setup语法实现:
<template>
<div>
<div>{{ formattedTime }}</div>
<button @click="startTimer" :disabled="timer">Start</button>
<button @click="stopTimer" :disabled="!timer">Stop</button>
</div>
</template>
<script>
import { ref, computed, onBeforeUnmount } from 'vue'
export default {
setup() {
const seconds = ref(0)
const timer = ref(null)
const formattedTime = computed(() => {
const hours = Math.floor(seconds.value / 3600)
const minutes = Math.floor((seconds.value % 3600) / 60)
const secs = seconds.value % 60
return [
hours.toString().padStart(2, '0'),
minutes.toString().padStart(2, '0'),
secs.toString().padStart(2, '0')
].join(':')
})
function startTimer() {
timer.value = setInterval(() => {
seconds.value++
}, 1000)
}
function stopTimer() {
clearInterval(timer.value)
timer.value = null
}
onBeforeUnmount(() => {
if (timer.value) {
clearInterval(timer.value)
}
})
return {
seconds,
timer,
formattedTime,
startTimer,
stopTimer
}
}
}
</script>






