vue实现单词拼写
Vue 实现单词拼写功能
在 Vue 中实现单词拼写功能,可以通过动态绑定输入框和实时校验拼写正确性来完成。以下是具体实现方法:
数据绑定与输入监听
在 Vue 组件中定义数据模型,绑定到输入框并通过 v-model 监听输入变化:

<template>
<div>
<p>拼写单词: {{ targetWord }}</p>
<input v-model="userInput" @input="checkSpelling" />
<p v-if="isCorrect">拼写正确!</p>
<p v-else>请继续尝试</p>
</div>
</template>
<script>
export default {
data() {
return {
targetWord: "example",
userInput: "",
isCorrect: false
};
}
};
</script>
拼写校验逻辑
在 methods 中添加校验方法,比较用户输入与目标单词:

methods: {
checkSpelling() {
this.isCorrect = this.userInput.toLowerCase() === this.targetWord.toLowerCase();
}
}
进阶功能:随机单词生成
可以扩展功能,每次随机选择不同的单词进行拼写练习:
data() {
return {
wordList: ["apple", "banana", "orange", "grape"],
targetWord: "",
// ...其他数据
};
},
created() {
this.pickRandomWord();
},
methods: {
pickRandomWord() {
const randomIndex = Math.floor(Math.random() * this.wordList.length);
this.targetWord = this.wordList[randomIndex];
this.userInput = "";
this.isCorrect = false;
},
// ...其他方法
}
视觉反馈增强
通过 CSS 类绑定提供更直观的反馈:
<input
v-model="userInput"
@input="checkSpelling"
:class="{ 'correct': isCorrect, 'incorrect': !isCorrect && userInput }"
/>
.correct {
border: 2px solid green;
}
.incorrect {
border: 2px solid red;
}
完整组件示例
<template>
<div class="spelling-game">
<h3>拼写单词: {{ targetWord }}</h3>
<input
v-model="userInput"
@input="checkSpelling"
:class="{ 'correct': isCorrect, 'incorrect': !isCorrect && userInput }"
/>
<p v-if="isCorrect" class="success-message">拼写正确!</p>
<button @click="pickRandomWord" v-if="isCorrect">下一个单词</button>
</div>
</template>
<script>
export default {
data() {
return {
wordList: ["apple", "banana", "orange", "grape"],
targetWord: "",
userInput: "",
isCorrect: false
};
},
created() {
this.pickRandomWord();
},
methods: {
checkSpelling() {
this.isCorrect = this.userInput.toLowerCase() === this.targetWord.toLowerCase();
},
pickRandomWord() {
const randomIndex = Math.floor(Math.random() * this.wordList.length);
this.targetWord = this.wordList[randomIndex];
this.userInput = "";
this.isCorrect = false;
}
}
};
</script>
<style>
.correct {
border: 2px solid green;
}
.incorrect {
border: 2px solid red;
}
.success-message {
color: green;
font-weight: bold;
}
</style>
这个实现提供了基本的单词拼写功能,包括随机单词选择、实时校验和视觉反馈。可以根据需要进一步扩展,如添加音标显示、发音功能或积分系统等。






