vue实现正计时
Vue 实现正计时的方法
使用 setInterval 实现基础正计时
在 Vue 组件的 data 中定义计时器变量和当前时间:
data() {
return {
timer: null,
seconds: 0
}
}
在 methods 中创建开始计时的方法:
startTimer() {
this.timer = setInterval(() => {
this.seconds++
}, 1000)
}
在 mounted 生命周期钩子中启动计时器:
mounted() {
this.startTimer()
}
在组件销毁时清除计时器:
beforeDestroy() {
clearInterval(this.timer)
}
格式化显示时间
添加一个计算属性来格式化显示的时间:
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')}`
}
}
在模板中使用:
<template>
<div>{{ formattedTime }}</div>
</template>
使用 Composition API 实现
对于 Vue 3,可以使用 Composition API:
import { ref, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const seconds = ref(0)
let timer = null
const startTimer = () => {
timer = setInterval(() => {
seconds.value++
}, 1000)
}
onMounted(() => {
startTimer()
})
onUnmounted(() => {
clearInterval(timer)
})
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')}`
})
return {
formattedTime
}
}
}
添加暂停和继续功能
扩展功能实现暂停和继续:

data() {
return {
isPaused: false
}
},
methods: {
toggleTimer() {
this.isPaused = !this.isPaused
if (this.isPaused) {
clearInterval(this.timer)
} else {
this.startTimer()
}
}
}
使用第三方库
对于更复杂的需求,可以考虑使用第三方库如 vue-countup 或 moment.js 来处理时间格式化和显示。






