用vue实现打字测速
实现思路
使用Vue构建一个打字速度测试应用,核心功能包括计时、计算打字速度(字符/分钟或单词/分钟)以及准确率统计。需监听用户输入并与目标文本比对。
核心代码实现
模板部分
<template>
<div class="typing-test">
<h3>目标文本</h3>
<div class="target-text">{{ targetText }}</div>
<h3>你的输入</h3>
<textarea
v-model="userInput"
@input="checkInput"
:disabled="isCompleted"
></textarea>
<div v-if="startTime">
<p>用时: {{ elapsedTime }}秒</p>
<p>速度: {{ typingSpeed }} CPM (字符/分钟)</p>
<p>准确率: {{ accuracy }}%</p>
</div>
<button v-if="isCompleted" @click="resetTest">重新测试</button>
</div>
</template>
脚本部分

<script>
export default {
data() {
return {
targetText: 'The quick brown fox jumps over the lazy dog',
userInput: '',
startTime: null,
endTime: null,
isCompleted: false
}
},
computed: {
elapsedTime() {
if (!this.startTime) return 0;
const end = this.endTime || Date.now();
return ((end - this.startTime) / 1000).toFixed(2);
},
typingSpeed() {
if (!this.startTime) return 0;
const minutes = this.elapsedTime / 60;
return Math.round(this.userInput.length / minutes);
},
accuracy() {
let correctChars = 0;
for (let i = 0; i < this.userInput.length; i++) {
if (this.userInput[i] === this.targetText[i]) {
correctChars++;
}
}
return ((correctChars / this.userInput.length) * 100).toFixed(2);
}
},
methods: {
checkInput() {
if (!this.startTime) {
this.startTime = Date.now();
}
if (this.userInput === this.targetText) {
this.endTime = Date.now();
this.isCompleted = true;
}
},
resetTest() {
this.userInput = '';
this.startTime = null;
this.endTime = null;
this.isCompleted = false;
}
}
}
</script>
样式优化
<style scoped>
.typing-test {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.target-text {
background: #f5f5f5;
padding: 15px;
margin-bottom: 20px;
border-radius: 4px;
}
textarea {
width: 100%;
height: 150px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
resize: none;
}
button {
margin-top: 20px;
padding: 10px 20px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
功能扩展建议
-
多语言支持 添加不同语言的测试文本库,让用户可以选择不同语言进行测试。
-
难度分级 实现简单、中等、困难三个级别的测试文本,长度和复杂度逐渐增加。

-
历史记录 使用localStorage保存用户的测试历史,显示最高速度和平均速度等统计数据。
-
实时反馈 在用户输入时,实时标记正确和错误的字符,提供更直观的反馈。
-
音效提示 在测试完成时添加音效反馈,增强用户体验。






