vue实现计时
Vue 计时器实现方法
使用 data 和 setInterval
在 Vue 组件的 data 中定义计时器变量和计时器实例,通过 setInterval 实现计时功能。
export default {
data() {
return {
timer: null,
seconds: 0
}
},
methods: {
startTimer() {
this.timer = setInterval(() => {
this.seconds++
}, 1000)
},
stopTimer() {
clearInterval(this.timer)
this.timer = null
},
resetTimer() {
this.seconds = 0
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
使用 computed 计算显示时间
通过 computed 属性将秒数转换为更友好的时间格式。
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')}`
}
}
使用 Vue 生命周期钩子
在 mounted 钩子中自动启动计时器,在 beforeDestroy 钩子中清除计时器。
mounted() {
this.startTimer()
},
beforeDestroy() {
this.stopTimer()
}
使用 Composition API
对于 Vue 3 或使用 Composition API 的 Vue 2 项目,可以使用 ref 和 onUnmounted 实现。
import { ref, onUnmounted } from 'vue'
export default {
setup() {
const seconds = ref(0)
let timer = null
const startTimer = () => {
timer = setInterval(() => {
seconds.value++
}, 1000)
}
const stopTimer = () => {
clearInterval(timer)
}
onUnmounted(() => {
stopTimer()
})
return {
seconds,
startTimer,
stopTimer
}
}
}
实现暂停/继续功能
扩展计时器功能,添加暂停和继续逻辑。
data() {
return {
isPaused: false,
// 其他数据...
}
},
methods: {
pauseTimer() {
clearInterval(this.timer)
this.isPaused = true
},
resumeTimer() {
if (this.isPaused) {
this.startTimer()
this.isPaused = false
}
}
}
使用第三方库
对于更复杂的计时需求,可以考虑使用专门的时间处理库如 date-fns 或 moment.js 来辅助处理时间格式和计算。

import { format } from 'date-fns'
computed: {
formattedTime() {
const date = new Date(0)
date.setSeconds(this.seconds)
return format(date, 'HH:mm:ss')
}
}






