vue实现计时功能
Vue 实现计时功能的方法
使用 setInterval 实现基础计时器
在 Vue 中可以通过 data 定义计时器状态,结合 setInterval 实现计时功能。以下是一个简单的倒计时示例:

<template>
<div>
<p>{{ time }}</p>
<button @click="startTimer">开始</button>
<button @click="stopTimer">停止</button>
</div>
</template>
<script>
export default {
data() {
return {
time: 0,
timer: null
}
},
methods: {
startTimer() {
this.timer = setInterval(() => {
this.time++
}, 1000)
},
stopTimer() {
clearInterval(this.timer)
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
使用计算属性格式化时间
通过计算属性将秒数格式化为 HH:MM:SS 形式,提升可读性:

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')}`
}
}
使用 Vue Composition API(Vue 3)
在 Vue 3 中可以通过 ref 和 onMounted 等组合式 API 实现:
<template>
<div>{{ formattedTime }}</div>
</template>
<script setup>
import { ref, computed, onUnmounted } from 'vue'
const time = ref(0)
const timer = ref(null)
const startTimer = () => {
timer.value = setInterval(() => {
time.value++
}, 1000)
}
const formattedTime = computed(() => {
const hours = Math.floor(time.value / 3600)
const minutes = Math.floor((time.value % 3600) / 60)
const seconds = time.value % 60
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})
onUnmounted(() => {
clearInterval(timer.value)
})
</script>
使用第三方库
对于复杂计时需求,可以考虑使用专门的时间处理库如 day.js 或 moment.js:
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
// 在方法中使用
formatTime(seconds) {
return dayjs.duration(seconds, 'seconds').format('HH:mm:ss')
}
注意事项
- 组件销毁时需要清除定时器(
beforeDestroy或onUnmounted) - 避免内存泄漏,确保定时器被正确清理
- 对于高精度计时需求,建议使用
performance.now()替代Date.now() - 移动端注意页面隐藏时的定时器处理(可通过
Page Visibility API优化)






