用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,
timerInterval: null
}
},
computed: {
formattedTime() {
const totalSeconds = Math.floor(this.elapsedTime / 1000)
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
const milliseconds = Math.floor((this.elapsedTime % 1000) / 10)
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(2, '0')}`
}
},
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.isRunning = false
this.elapsedTime = 0
},
updateTime() {
this.elapsedTime = Date.now() - this.startTime
}
},
beforeUnmount() {
clearInterval(this.timerInterval)
}
}
</script>
样式部分
<style scoped>
.stopwatch {
text-align: center;
margin: 20px;
font-family: Arial, sans-serif;
}
.display {
font-size: 3em;
margin-bottom: 20px;
}
.controls button {
margin: 0 5px;
padding: 8px 16px;
font-size: 1em;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
功能说明
- 计时显示:格式为"分钟:秒.毫秒"(MM:SS.MS)
- 开始按钮:启动计时器,开始计时
- 暂停按钮:暂停当前计时,保留已计时间
- 重置按钮:将计时归零,停止任何正在进行的计时
- 状态控制:按钮在适当状态下禁用(如运行时禁用开始按钮)
扩展建议
- 添加计次功能,记录多个分段时间
- 实现本地存储,保存历史计时记录
- 增加声音提示功能
- 添加主题切换或自定义样式选项







