vue实现打字练习功能

实现思路
在Vue中实现打字练习功能,核心在于动态渲染文本、监听用户输入、匹配输入内容以及计算打字速度和准确率。主要分为文本展示、输入匹配、计时统计三个模块。
核心代码实现
模板部分
<template>
<div class="typing-practice">
<div class="text-display">
<span
v-for="(char, index) in textChars"
:key="index"
:class="{
'correct': index < currentIndex && char === inputChars[index],
'wrong': index < currentIndex && char !== inputChars[index],
'current': index === currentIndex
}"
>
{{ char }}
</span>
</div>
<input
v-model="userInput"
@input="handleInput"
@keydown.delete="handleBackspace"
placeholder="开始打字..."
/>
<div class="stats">
<p>速度: {{ wpm }} WPM</p>
<p>准确率: {{ accuracy }}%</p>
<p>用时: {{ elapsedTime }}秒</p>
</div>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
practiceText: 'The quick brown fox jumps over the lazy dog',
userInput: '',
currentIndex: 0,
startTime: null,
elapsedTime: 0,
correctCount: 0,
timer: null
}
},
computed: {
textChars() {
return this.practiceText.split('')
},
inputChars() {
return this.userInput.split('')
},
wpm() {
const minutes = this.elapsedTime / 60
return minutes > 0
? Math.round((this.correctCount / 5) / minutes)
: 0
},
accuracy() {
return this.currentIndex > 0
? Math.round((this.correctCount / this.currentIndex) * 100)
: 0
}
},
methods: {
handleInput() {
if (!this.startTime) {
this.startTime = new Date()
this.startTimer()
}
const inputLength = this.userInput.length
if (inputLength > this.practiceText.length) {
this.userInput = this.userInput.slice(0, this.practiceText.length)
return
}
this.currentIndex = inputLength
if (this.textChars[inputLength - 1] === this.inputChars[inputLength - 1]) {
this.correctCount++
}
},
handleBackspace(e) {
if (this.userInput.length === 0) {
e.preventDefault()
}
},
startTimer() {
this.timer = setInterval(() => {
this.elapsedTime = Math.floor((new Date() - this.startTime) / 1000)
}, 1000)
}
},
beforeUnmount() {
clearInterval(this.timer)
}
}
</script>
样式部分
<style scoped>
.typing-practice {
font-family: monospace;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.text-display {
font-size: 24px;
margin-bottom: 20px;
line-height: 1.5;
white-space: pre-wrap;
}
.correct {
color: green;
}
.wrong {
color: red;
text-decoration: underline;
}
.current {
background-color: #eee;
border-left: 2px solid #333;
animation: blink 1s infinite;
}
@keyframes blink {
50% {
border-left-color: transparent;
}
}
input {
width: 100%;
padding: 10px;
font-size: 18px;
font-family: monospace;
}
.stats {
margin-top: 20px;
display: flex;
justify-content: space-between;
}
</style>
功能扩展建议
- 多文本支持:创建文本库,随机选择或按难度分级练习文本
- 进度保存:使用localStorage保存用户练习记录和统计数据
- 错误分析:记录常见错误字符,提供针对性练习
- 音效反馈:添加正确/错误的音效增强交互体验
- 多人模式:通过WebSocket实现多人打字比赛功能
性能优化方向
- 虚拟滚动:对于长文本实现虚拟滚动优化渲染性能
- 防抖处理:对高频输入事件进行防抖处理
- Web Worker:将统计计算移入Web Worker避免阻塞UI
该实现包含了打字练习的核心功能,可根据实际需求进一步扩展和完善。







