vue实现计时
Vue 实现计时功能
在 Vue 中实现计时功能可以通过多种方式完成,以下是几种常见的方法:
使用 setInterval 实现基础计时器
通过 setInterval 和 clearInterval 控制计时器的启动和停止。在 Vue 的 data 中定义计时器变量和计时数值。
<template>
<div>
<p>{{ time }}</p>
<button @click="startTimer">开始</button>
<button @click="stopTimer">停止</button>
<button @click="resetTimer">重置</button>
</div>
</template>
<script>
export default {
data() {
return {
time: 0,
timer: null
}
},
methods: {
startTimer() {
if (!this.timer) {
this.timer = setInterval(() => {
this.time++
}, 1000)
}
},
stopTimer() {
clearInterval(this.timer)
this.timer = null
},
resetTimer() {
this.stopTimer()
this.time = 0
}
},
beforeDestroy() {
this.stopTimer()
}
}
</script>
使用 Vue 的计算属性格式化时间
将秒数格式化为更易读的 HH:MM:SS 格式,可以通过计算属性实现。

<template>
<div>
<p>{{ formattedTime }}</p>
</div>
</template>
<script>
export default {
data() {
return {
time: 3665 // 示例:1小时1分钟5秒
}
},
computed: {
formattedTime() {
const hours = Math.floor(this.time / 3600)
const minutes = Math.floor((this.time % 3600) / 60)
const seconds = this.time % 60
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}
}
}
</script>
使用第三方库(如 day.js)
对于更复杂的时间处理,可以引入 day.js 或其他日期库来简化时间格式化。
安装 day.js:

npm install day.js
在 Vue 中使用:
<template>
<div>
<p>{{ formattedTime }}</p>
</div>
</template>
<script>
import dayjs from 'dayjs'
export default {
data() {
return {
time: 3665
}
},
computed: {
formattedTime() {
return dayjs().startOf('day').second(this.time).format('HH:mm:ss')
}
}
}
</script>
使用 Vue 3 Composition API
在 Vue 3 中,可以通过 ref 和 onMounted 等组合式 API 实现计时器。
<template>
<div>
<p>{{ time }}</p>
<button @click="startTimer">开始</button>
<button @click="stopTimer">停止</button>
</div>
</template>
<script>
import { ref, onBeforeUnmount } from 'vue'
export default {
setup() {
const time = ref(0)
let timer = null
const startTimer = () => {
if (!timer) {
timer = setInterval(() => {
time.value++
}, 1000)
}
}
const stopTimer = () => {
clearInterval(timer)
timer = null
}
onBeforeUnmount(() => {
stopTimer()
})
return {
time,
startTimer,
stopTimer
}
}
}
</script>
注意事项
- 在组件销毁时(
beforeDestroy或onBeforeUnmount)清除计时器,避免内存泄漏。 - 如果需要暂停和继续功能,可以记录暂停时的时间点,并在继续时从该时间点恢复。
- 对于高精度计时需求,可以使用
requestAnimationFrame替代setInterval。






