vue实现秒表组件

实现秒表组件的基本思路
使用Vue实现秒表组件需要管理时间状态、控制计时器的启动/暂停/重置功能,并通过计算属性动态显示格式化时间。核心逻辑包括利用setInterval更新计时数据,并通过生命周期钩子清除计时器避免内存泄漏。
定义组件模板结构
<template>
<div class="stopwatch">
<div class="display">{{ formattedTime }}</div>
<div class="controls">
<button @click="start" :disabled="isRunning">Start</button>
<button @click="pause" :disabled="!isRunning">Pause</button>
<button @click="reset">Reset</button>
</div>
</div>
</template>
脚本部分实现
<script>
export default {
data() {
return {
isRunning: false,
elapsedTime: 0,
timer: null
}
},
computed: {
formattedTime() {
const date = new Date(this.elapsedTime);
const minutes = date.getUTCMinutes().toString().padStart(2, '0');
const seconds = date.getUTCSeconds().toString().padStart(2, '0');
const milliseconds = Math.floor(date.getUTCMilliseconds() / 10).toString().padStart(2, '0');
return `${minutes}:${seconds}.${milliseconds}`;
}
},
methods: {
start() {
if (!this.isRunning) {
const startTime = Date.now() - this.elapsedTime;
this.timer = setInterval(() => {
this.elapsedTime = Date.now() - startTime;
}, 10);
this.isRunning = true;
}
},
pause() {
clearInterval(this.timer);
this.isRunning = false;
},
reset() {
clearInterval(this.timer);
this.isRunning = false;
this.elapsedTime = 0;
}
},
beforeUnmount() {
clearInterval(this.timer);
}
}
</script>
样式优化建议
<style scoped>
.stopwatch {
text-align: center;
font-family: sans-serif;
}
.display {
font-size: 3em;
margin-bottom: 20px;
}
button {
background: #42b983;
color: white;
border: none;
padding: 8px 16px;
margin: 0 5px;
border-radius: 4px;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
功能扩展建议
- 添加分段计时功能(Lap Time):记录多个时间节点
- 增加声音提示:到达特定时间时播放提示音
- 持久化存储:使用localStorage保存历史记录
- 精度调整:允许切换毫秒/秒级精度显示
注意事项
- 使用
beforeUnmount生命周期确保组件销毁时清除计时器 - 时间计算采用
Date.now()而非直接累加,避免误差累积 - 按钮状态通过
isRunning动态控制,防止重复启动 - 格式化显示时注意补零操作(
padStart方法)保持统一格式







