vue实现秒表
实现秒表功能
使用Vue实现秒表功能需要结合数据绑定、计算属性和定时器。以下是一个完整的实现方案:
创建Vue组件
<template>
<div class="stopwatch">
<div class="display">{{ formattedTime }}</div>
<div class="controls">
<button @click="start" :disabled="isRunning">开始</button>
<button @click="stop" :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 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.timer = setInterval(this.updateTime, 10)
this.isRunning = true
}
},
stop() {
if (this.isRunning) {
clearInterval(this.timer)
this.isRunning = false
}
},
reset() {
clearInterval(this.timer)
this.isRunning = false
this.elapsedTime = 0
},
updateTime() {
this.elapsedTime = Date.now() - this.startTime
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style scoped>
.stopwatch {
text-align: center;
margin: 20px;
}
.display {
font-size: 3em;
margin-bottom: 20px;
font-family: monospace;
}
button {
padding: 8px 16px;
margin: 0 5px;
font-size: 1em;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
功能说明
-
数据属性

isRunning:跟踪秒表是否正在运行startTime:记录开始时间戳elapsedTime:存储经过的毫秒数timer:存储定时器引用
-
计算属性

formattedTime:将毫秒转换为"MM:SS.mm"格式的字符串
-
方法
start():启动秒表stop():暂停秒表reset():重置秒表updateTime():更新经过的时间
-
生命周期钩子
beforeDestroy:组件销毁前清除定时器
使用方式
- 将此组件导入到需要使用的地方
- 在模板中使用
<stopwatch></stopwatch>标签 - 秒表显示格式为"分钟:秒.毫秒"(如01:23.45)
进阶优化
- 添加圈数记录功能
- 实现不同主题样式
- 添加声音提示
- 支持键盘快捷键操作
- 将计时数据持久化到本地存储
这个实现提供了基本的秒表功能,可以根据具体需求进行扩展和定制。






