html使用vue实现秒表
使用Vue实现秒表
以下是一个基于Vue.js实现的秒表组件,包含开始、暂停、重置功能。

创建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 {
startTime: 0,
elapsedTime: 0,
timerInterval: null,
isRunning: false
}
},
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.timerInterval = setInterval(this.updateTime, 10)
this.isRunning = true
}
},
pause() {
if (this.isRunning) {
clearInterval(this.timerInterval)
this.isRunning = false
}
},
reset() {
clearInterval(this.timerInterval)
this.elapsedTime = 0
this.isRunning = false
},
updateTime() {
this.elapsedTime = Date.now() - this.startTime
}
}
}
</script>
<style>
.stopwatch {
text-align: center;
font-family: Arial, sans-serif;
}
.display {
font-size: 2.5em;
margin-bottom: 20px;
}
.controls button {
padding: 8px 16px;
margin: 0 5px;
font-size: 1em;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
使用组件
- 在Vue项目中注册并使用该组件:
import Stopwatch from './Stopwatch.vue'
export default {
components: {
Stopwatch
}
}
- 在模板中使用:
<stopwatch />
功能说明
- 开始按钮:启动计时器,从0开始计时或从暂停的位置继续计时
- 暂停按钮:暂停当前计时,保持显示当前时间
- 重置按钮:将计时器归零,停止任何正在进行的计时
实现原理
- 使用
Date.now()获取精确的时间戳 - 通过
setInterval每10毫秒更新一次显示时间 - 计算经过的时间差并格式化为
HH:MM:SS.ms的显示格式 - 使用Vue的响应式数据自动更新显示
扩展功能
如需添加更多功能,如计次功能,可以扩展组件:
data() {
return {
// 原有数据
laps: []
}
},
methods: {
// 原有方法
recordLap() {
this.laps.push(this.formattedTime)
}
}
然后在模板中添加:
<button @click="recordLap">计次</button>
<ul>
<li v-for="(lap, index) in laps" :key="index">{{ lap }}</li>
</ul>







