vue实现秒表组件
实现思路
Vue实现秒表组件主要依靠计算时间差、动态更新显示以及控制开始、暂停和重置功能。通过Date对象记录时间戳,结合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 {
startTime: 0,
elapsedTime: 0,
isRunning: false,
timerInterval: 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) {
this.startTime = Date.now() - this.elapsedTime
this.timerInterval = setInterval(() => {
this.elapsedTime = Date.now() - this.startTime
}, 10)
this.isRunning = true
}
},
pause() {
clearInterval(this.timerInterval)
this.isRunning = false
},
reset() {
clearInterval(this.timerInterval)
this.isRunning = false
this.elapsedTime = 0
}
}
}
</script>
样式部分
<style scoped>
.stopwatch {
text-align: center;
font-family: Arial, sans-serif;
}
.display {
font-size: 3em;
margin: 20px;
}
button {
padding: 10px 20px;
margin: 5px;
font-size: 1em;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
功能说明
- 开始计时:记录当前时间戳作为起点,通过
setInterval每10毫秒更新一次时间差 - 暂停计时:清除定时器并保留当前时间值
- 重置计时:清除定时器并将时间归零
- 时间显示:格式化为
MM:SS.MS,自动补零保持两位数显示
优化建议
- 性能优化:将定时器间隔调整为
requestAnimationFrame实现更流畅的动画效果 - 功能扩展:添加分段计时(Lap)功能,记录多个时间点
- 持久化:结合
localStorage实现关闭页面后恢复上次计时状态
完整组件可直接复制使用,或通过npm install安装第三方库如vue-stopwatch获得更丰富功能。





