vue实现秒表
实现秒表功能
在Vue中实现秒表功能需要处理计时逻辑、显示格式以及控制按钮(开始、暂停、重置)。以下是具体实现步骤:
创建Vue组件
<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,
startTime: 0,
elapsedTime: 0,
timerInterval: null
}
}
}
</script>
实现计时逻辑
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() {
if (this.isRunning) {
clearInterval(this.timerInterval)
this.isRunning = false
}
},
reset() {
clearInterval(this.timerInterval)
this.isRunning = false
this.elapsedTime = 0
}
}
格式化显示时间
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}`
}
}
添加基本样式
<style scoped>
.stopwatch {
text-align: center;
margin: 20px;
}
.display {
font-size: 3em;
margin-bottom: 20px;
font-family: monospace;
}
button {
margin: 0 5px;
padding: 8px 16px;
font-size: 1em;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
功能扩展建议
如果需要更精确的计时,可以考虑使用requestAnimationFrame代替setInterval:
start() {
if (!this.isRunning) {
this.startTime = Date.now() - this.elapsedTime
const update = () => {
this.elapsedTime = Date.now() - this.startTime
if (this.isRunning) {
requestAnimationFrame(update)
}
}
this.isRunning = true
requestAnimationFrame(update)
}
}
注意事项
组件销毁时应清除计时器:
beforeDestroy() {
clearInterval(this.timerInterval)
}
这种实现方式提供了基本的秒表功能,可以根据需要进一步扩展,如添加圈数记录、更精确的时间显示格式等。







