vue实现秒表组件
实现秒表组件的基本思路
使用Vue实现秒表组件需要处理时间显示、开始、暂停、重置等基本功能。核心逻辑包括计时器的启动、暂停和清零,同时正确显示格式化的时间。
基础秒表组件代码示例
<template>
<div class="stopwatch">
<div class="display">{{ formattedTime }}</div>
<button @click="start" :disabled="isRunning">Start</button>
<button @click="pause" :disabled="!isRunning">Pause</button>
<button @click="reset">Reset</button>
</div>
</template>
<script>
export default {
data() {
return {
isRunning: false,
startTime: 0,
elapsedTime: 0,
timer: 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.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
}
}
}
</script>
功能扩展建议
添加圈数记录功能可以让秒表更加实用。在组件中添加一个列表来存储每次记录的圈数时间。
<template>
<div>
<!-- 原有代码 -->
<button @click="lap">Lap</button>
<ul>
<li v-for="(lap, index) in laps" :key="index">
Lap {{ index + 1 }}: {{ formatLapTime(lap) }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
laps: []
}
},
methods: {
lap() {
if (this.isRunning) {
this.laps.push(this.elapsedTime)
}
},
formatLapTime(time) {
// 复用formattedTime的计算逻辑或单独实现
}
}
}
</script>
性能优化考虑
对于高精度计时需求,使用requestAnimationFrame替代setInterval可以获得更平滑的动画效果和更精确的时间计算。
methods: {
start() {
if (!this.isRunning) {
this.startTime = Date.now() - this.elapsedTime
this.isRunning = true
this.update()
}
},
update() {
if (this.isRunning) {
this.elapsedTime = Date.now() - this.startTime
requestAnimationFrame(this.update)
}
}
}
样式美化建议
添加CSS样式可以提升秒表组件的视觉效果。以下是一个简单的样式示例:
.stopwatch {
text-align: center;
font-family: Arial, sans-serif;
}
.display {
font-size: 3em;
margin: 20px 0;
}
button {
background: #42b983;
color: white;
border: none;
padding: 10px 20px;
margin: 0 5px;
border-radius: 5px;
cursor: pointer;
}
button:disabled {
background: #cccccc;
cursor: not-allowed;
}
ul {
list-style: none;
padding: 0;
margin-top: 20px;
}
组件封装与复用
将秒表组件封装为可复用的Vue组件,可以通过props接收自定义配置,如时间格式、按钮样式等,并通过emit事件与父组件通信。

props: {
autoStart: {
type: Boolean,
default: false
},
timeFormat: {
type: String,
default: 'mm:ss.SS'
}
},
mounted() {
if (this.autoStart) {
this.start()
}
}





