html使用vue实现秒表
使用Vue实现秒表
以下是一个基于Vue的秒表实现方案,包含开始、暂停、重置功能,并显示时、分、秒和毫秒。
核心代码实现
<template>
<div class="stopwatch">
<div class="display">{{ formattedTime }}</div>
<div class="controls">
<button @click="start" :disabled="isRunning">开始</button>
<button @click="pause" :disabled="!isRunning">暂停</button>
<button @click="reset">重置</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isRunning: false,
startTime: 0,
elapsedTime: 0,
timer: null
}
},
computed: {
formattedTime() {
const date = new Date(this.elapsedTime)
const hours = date.getUTCHours().toString().padStart(2, '0')
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 `${hours}:${minutes}:${seconds}.${milliseconds}`
}
},
methods: {
start() {
if (!this.isRunning) {
this.startTime = Date.now() - this.elapsedTime
this.timer = setInterval(this.update, 10)
this.isRunning = true
}
},
pause() {
if (this.isRunning) {
clearInterval(this.timer)
this.isRunning = false
}
},
reset() {
clearInterval(this.timer)
this.isRunning = false
this.elapsedTime = 0
},
update() {
this.elapsedTime = Date.now() - this.startTime
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style>
.stopwatch {
text-align: center;
font-family: Arial, sans-serif;
}
.display {
font-size: 3em;
margin: 20px 0;
}
button {
margin: 0 5px;
padding: 8px 16px;
font-size: 1em;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
实现要点
-
数据状态管理
isRunning跟踪秒表是否正在运行startTime记录开始时间戳elapsedTime存储累计时间(毫秒)timer保存定时器引用
-
时间格式化
- 使用Date对象将毫秒转换为可读格式
- 通过
padStart确保两位数显示 - 毫秒显示两位数(实际精度为10ms)
-
控制方法

start()启动计时器并更新状态pause()停止计时器并保持当前时间reset()完全重置所有状态update()计算并更新当前经过时间
-
生命周期管理
- 在组件销毁前清除定时器防止内存泄漏
扩展功能建议
-
添加圈数记录功能

data() { return { laps: [] } }, methods: { recordLap() { this.laps.push(this.formattedTime) } } -
提高时间精度 将定时器间隔改为1ms(注意浏览器最低间隔限制)
-
持久化存储 使用localStorage保存历史记录
-
动画效果 添加CSS过渡效果增强用户体验
该实现提供了秒表的基本功能,可以根据需求进一步扩展和完善。






