vue实现填空答题功能
Vue实现填空答题功能
实现填空答题功能需要结合Vue的数据绑定和事件处理机制。以下是一个完整的实现方案:
数据准备
定义题目数据结构和用户答案存储对象:
data() {
return {
questions: [
{
id: 1,
content: 'Vue的核心特性包括__和__',
blanks: [2], // 表示需要填空的数量
answers: ['响应式', '组件化'] // 正确答案
},
// 更多题目...
],
userAnswers: {} // 存储用户答案 {questionId: [answer1, answer2...]}
}
}
模板渲染
使用v-for渲染题目,动态生成填空输入框:
<div v-for="question in questions" :key="question.id">
<p v-html="renderQuestion(question)"></p>
<div v-for="(blank, index) in question.blanks[0]" :key="index">
<input
v-model="userAnswers[question.id][index]"
@input="checkAnswer(question.id, index)"
:class="{correct: isCorrect(question.id, index)}"
>
</div>
</div>
方法实现
添加核心处理方法:

methods: {
renderQuestion(question) {
return question.content.replace(/__/g, '<span class="blank"></span>')
},
checkAnswer(questionId, blankIndex) {
const question = this.questions.find(q => q.id === questionId)
const isCorrect = this.userAnswers[questionId][blankIndex] === question.answers[blankIndex]
// 可以添加答对/答错的反馈逻辑
},
isCorrect(questionId, blankIndex) {
const question = this.questions.find(q => q.id === questionId)
return this.userAnswers[questionId] &&
this.userAnswers[questionId][blankIndex] === question.answers[blankIndex]
}
}
样式优化
添加CSS使填空更直观:
.blank {
display: inline-block;
width: 100px;
border-bottom: 1px solid #333;
margin: 0 5px;
}
input.correct {
border: 2px solid green;
background-color: #e8f5e9;
}
进阶功能
可以扩展以下功能:

-
添加填空题自动批改功能
calculateScore() { return this.questions.reduce((score, question) => { const userAnswer = this.userAnswers[question.id] || [] const correctCount = question.answers.filter((ans, i) => userAnswer[i] === ans ).length return score + (correctCount / question.answers.length) }, 0) } -
实现填空题的拖拽填空交互
<draggable v-model="dragOptions" @end="onDragEnd"> <!-- 可拖拽选项 --> </draggable> -
添加填空题的提示功能
showHint(questionId) { const question = this.questions.find(q => q.id === questionId) // 显示第一个空的提示 alert(`提示:${question.answers[0].charAt(0)}...`) }
这个实现方案涵盖了填空题的基本功能,可以根据实际需求进行扩展和优化。






