vue实现秒表组件
实现思路
使用Vue的响应式特性,通过data属性记录当前时间、计时状态及间隔ID。核心逻辑包括开始、暂停、继续和重置功能,利用setInterval实现计时更新。

基础代码结构
<template>
<div class="stopwatch">
<div class="display">{{ formattedTime }}</div>
<button @click="start" :disabled="isRunning">开始</button>
<button @click="pause" :disabled="!isRunning">暂停</button>
<button @click="reset" :disabled="!hasStarted">重置</button>
</div>
</template>
<script>
export default {
data() {
return {
startTime: 0,
elapsedTime: 0,
isRunning: false,
intervalId: null,
hasStarted: false
};
},
computed: {
formattedTime() {
const ms = this.elapsedTime % 1000;
const seconds = Math.floor(this.elapsedTime / 1000) % 60;
const minutes = Math.floor(this.elapsedTime / 60000) % 60;
const hours = Math.floor(this.elapsedTime / 3600000);
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`;
}
},
methods: {
start() {
this.startTime = Date.now() - this.elapsedTime;
this.isRunning = true;
this.hasStarted = true;
this.intervalId = setInterval(this.updateTime, 10);
},
pause() {
clearInterval(this.intervalId);
this.isRunning = false;
},
reset() {
clearInterval(this.intervalId);
this.elapsedTime = 0;
this.isRunning = false;
this.hasStarted = false;
},
updateTime() {
this.elapsedTime = Date.now() - this.startTime;
}
},
beforeDestroy() {
clearInterval(this.intervalId);
}
};
</script>
<style scoped>
.stopwatch {
text-align: center;
font-family: monospace;
}
.display {
font-size: 2em;
margin-bottom: 10px;
}
button {
margin: 0 5px;
padding: 5px 10px;
}
</style>
功能扩展
添加分段计时功能
在data中新增laps数组,并添加记录分段的方法:
data() {
return {
laps: []
};
},
methods: {
recordLap() {
this.laps.push(this.formattedTime);
}
}
优化性能
使用requestAnimationFrame替代setInterval:
start() {
this.startTime = Date.now() - this.elapsedTime;
this.isRunning = true;
const update = () => {
if (this.isRunning) {
this.elapsedTime = Date.now() - this.startTime;
requestAnimationFrame(update);
}
};
requestAnimationFrame(update);
}
注意事项
- 清除定时器:在组件销毁前通过
beforeDestroy钩子清除定时器,避免内存泄漏。 - 时间精度:根据需求调整
setInterval的间隔(如10ms),更高精度需使用performance.now()。 - 状态管理:通过
isRunning和hasStarted控制按钮的禁用状态,避免逻辑冲突。







