vue实现打字游戏
Vue 实现打字游戏的核心思路
使用 Vue 的数据绑定和响应式特性,结合键盘事件监听,实现动态文字输入检测与评分功能。关键点包括随机生成文本、实时匹配输入、计时与得分计算。
基础代码结构
<template>
<div class="typing-game">
<h3>剩余时间: {{ timeLeft }}秒</h3>
<p class="target-text">{{ targetText }}</p>
<input
v-model="userInput"
@input="checkInput"
placeholder="开始输入..."
/>
<p>得分: {{ score }}</p>
</div>
</template>
核心功能实现
<script>
export default {
data() {
return {
targetText: '',
userInput: '',
timeLeft: 60,
score: 0,
wordList: ['前端开发', 'Vue框架', '响应式编程', '组合式API', '虚拟DOM']
}
},
mounted() {
this.generateText();
this.startTimer();
},
methods: {
generateText() {
this.targetText = this.wordList[
Math.floor(Math.random() * this.wordList.length)
];
},
checkInput() {
if (this.userInput === this.targetText) {
this.score += 10;
this.userInput = '';
this.generateText();
}
},
startTimer() {
const timer = setInterval(() => {
this.timeLeft--;
if (this.timeLeft <= 0) {
clearInterval(timer);
alert(`游戏结束! 最终得分: ${this.score}`);
}
}, 1000);
}
}
}
</script>
样式优化建议
<style scoped>
.typing-game {
font-family: Arial;
max-width: 600px;
margin: 0 auto;
text-align: center;
}
.target-text {
font-size: 24px;
letter-spacing: 1px;
margin: 20px 0;
}
input {
width: 80%;
padding: 10px;
font-size: 16px;
}
</style>
高级功能扩展
动态难度调整
根据得分动态增加单词长度:

if (this.score > 30) {
this.wordList.push('组件化开发思想', '状态管理Vuex');
}
错误高亮显示
添加错误字符样式提示:
<p class="target-text">
<span
v-for="(char, index) in targetText"
:class="{ 'error': userInput[index] && userInput[index] !== char }"
>
{{ char }}
</span>
</p>
音效反馈
正确输入时播放提示音:

const audio = new Audio('correct.mp3');
audio.play();
性能优化建议
使用 Vue 的 computed 属性优化显示逻辑:
computed: {
displayText() {
return this.targetText.split('').map((char, i) => {
return {
char,
isCorrect: this.userInput[i] === char
};
});
}
}
游戏结束后禁用输入:
<input :disabled="timeLeft <= 0" />
注意事项
- 移动端需要额外处理虚拟键盘事件
- 考虑添加游戏重启按钮
- 对于长文本建议实现自动滚动
- 本地存储可用于保存最高分记录
通过以上方法可以构建一个完整的打字游戏,可根据需求进一步扩展多语言支持、用户等级系统等功能。






