vue实现打字游戏
实现思路
使用Vue实现打字游戏的核心在于动态渲染文本、监听用户输入、匹配字符并实时反馈。需要结合Vue的响应式数据绑定和键盘事件监听。

核心代码结构
<template>
<div class="typing-game">
<div class="target-text" ref="targetText">
<span
v-for="(char, index) in targetChars"
:key="index"
:class="getCharClass(index)"
>{{ char }}</span>
</div>
<input
type="text"
v-model="userInput"
@input="checkInput"
placeholder="开始输入..."
/>
<div class="stats">
进度: {{ currentIndex }}/{{ targetChars.length }} |
正确率: {{ accuracy }}%
</div>
</div>
</template>
数据与逻辑实现
<script>
export default {
data() {
return {
targetText: '这是一个示例文本,用于打字游戏练习。',
userInput: '',
currentIndex: 0,
correctCount: 0
}
},
computed: {
targetChars() {
return this.targetText.split('')
},
accuracy() {
return this.currentIndex > 0
? Math.round((this.correctCount / this.currentIndex) * 100)
: 0
}
},
methods: {
checkInput() {
const lastChar = this.userInput.slice(-1)
if (lastChar === this.targetChars[this.currentIndex]) {
this.correctCount++
}
this.currentIndex++
if (this.currentIndex >= this.targetChars.length) {
alert(`游戏结束!正确率: ${this.accuracy}%`)
this.resetGame()
}
},
getCharClass(index) {
return {
'correct': index < this.currentIndex &&
this.userInput[index] === this.targetChars[index],
'incorrect': index < this.currentIndex &&
this.userInput[index] !== this.targetChars[index],
'current': index === this.currentIndex
}
},
resetGame() {
this.userInput = ''
this.currentIndex = 0
this.correctCount = 0
}
}
}
</script>
样式设计
<style scoped>
.typing-game {
font-family: monospace;
font-size: 24px;
max-width: 800px;
margin: 0 auto;
}
.target-text span {
transition: all 0.2s;
}
.correct {
color: green;
}
.incorrect {
color: red;
text-decoration: underline;
}
.current {
background-color: yellow;
}
input {
width: 100%;
padding: 10px;
font-size: 20px;
margin-top: 20px;
}
.stats {
margin-top: 10px;
font-size: 16px;
}
</style>
功能扩展建议
- 增加难度选择:提供不同长度的文本或专业词汇库
- 计时功能:计算完成时间并显示打字速度(字/分钟)
- 随机文本:从API获取随机文本或使用用户自定义文本
- 音效反馈:正确/错误输入时播放不同音效
- 进度保存:使用localStorage保存用户最佳成绩
性能优化点
- 避免在模板中使用复杂的计算,将逻辑移到computed属性
- 对于超长文本,考虑虚拟滚动技术
- 使用防抖处理高频输入事件
- 预加载可能用到的所有文本资源
完整实现时可根据实际需求调整样式和交互细节,核心机制是通过比较用户输入与目标文本的字符来实现打字检测。






