vue实现秒表
实现秒表功能
在Vue中实现秒表功能可以通过以下方法完成,核心是使用setInterval计时器更新显示时间,并管理开始、暂停和重置逻辑。
定义数据与格式处理
在Vue组件的data中定义计时器相关变量:
data() {
return {
time: 0, // 毫秒数
isRunning: false, // 是否运行中
timer: null // 计时器实例
}
}
添加一个计算属性将毫秒转换为HH:MM:SS格式:
computed: {
formattedTime() {
const date = new Date(this.time);
return date.toISOString().substr(11, 8);
}
}
控制秒表的三个核心方法
开始计时方法:

start() {
if (!this.isRunning) {
const startTime = Date.now() - this.time;
this.timer = setInterval(() => {
this.time = Date.now() - startTime;
}, 10);
this.isRunning = true;
}
}
暂停计时方法:
pause() {
clearInterval(this.timer);
this.isRunning = false;
}
重置计时方法:

reset() {
clearInterval(this.timer);
this.time = 0;
this.isRunning = false;
}
模板部分实现
在模板中添加控制按钮和时间显示:
<template>
<div>
<h3>{{ formattedTime }}</h3>
<button @click="start" :disabled="isRunning">开始</button>
<button @click="pause" :disabled="!isRunning">暂停</button>
<button @click="reset">重置</button>
</div>
</template>
组件销毁时的清理
为避免内存泄漏,在组件销毁时清除计时器:
beforeDestroy() {
clearInterval(this.timer);
}
可选增强功能
需要更精确的计时可考虑使用performance.now()替代Date.now()。需要记录分段时间可添加一个数组存储时间点:
data() {
return {
laps: []
}
},
methods: {
recordLap() {
this.laps.push(this.formattedTime);
}
}
完整实现后,组件将显示格式化的时间,并提供开始、暂停和重置功能。按钮状态会根据计时器运行状态自动切换,确保操作逻辑的完整性。






