vue实现填空题
Vue 实现填空题的方法
在 Vue 中实现填空题功能,可以通过动态绑定输入框、条件渲染和状态管理来实现。以下是几种常见的实现方式:
使用 v-model 绑定输入框
通过 v-model 双向绑定输入框的值,实时更新用户输入的内容。这种方式适用于简单的填空题场景。
<template>
<div>
<p>请填空:{{ question }}</p>
<input v-model="userAnswer" placeholder="请输入答案" />
<button @click="checkAnswer">提交</button>
<p v-if="showResult">{{ result }}</p>
</div>
</template>
<script>
export default {
data() {
return {
question: "Vue 是一个 __ 框架",
correctAnswer: "前端",
userAnswer: "",
showResult: false,
result: ""
};
},
methods: {
checkAnswer() {
this.showResult = true;
this.result = this.userAnswer === this.correctAnswer ? "回答正确!" : "回答错误!";
}
}
};
</script>
动态生成填空题
如果需要动态生成多个填空题,可以使用 v-for 循环渲染输入框,并将用户输入存储在数组中。
<template>
<div>
<div v-for="(item, index) in questions" :key="index">
<p>{{ item.question }}</p>
<input v-model="userAnswers[index]" placeholder="请输入答案" />
</div>
<button @click="checkAllAnswers">提交</button>
<p v-if="showResult">{{ result }}</p>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
{ question: "Vue 是一个 __ 框架", answer: "前端" },
{ question: "Vue 的核心是 __", answer: "响应式" }
],
userAnswers: [],
showResult: false,
result: ""
};
},
methods: {
checkAllAnswers() {
const allCorrect = this.questions.every(
(item, index) => this.userAnswers[index] === item.answer
);
this.showResult = true;
this.result = allCorrect ? "全部回答正确!" : "有错误答案!";
}
}
};
</script>
填空题与文本混合
如果填空题需要嵌入到文本中,可以通过字符串替换或动态渲染的方式实现。
<template>
<div>
<p>请填空:{{ questionWithBlank }}</p>
<input v-model="userAnswer" placeholder="请输入答案" />
<button @click="checkAnswer">提交</button>
<p v-if="showResult">{{ result }}</p>
</div>
</template>
<script>
export default {
data() {
return {
question: "Vue 是一个 {blank} 框架",
correctAnswer: "前端",
userAnswer: "",
showResult: false,
result: ""
};
},
computed: {
questionWithBlank() {
return this.question.replace("{blank}", "_____");
}
},
methods: {
checkAnswer() {
this.showResult = true;
this.result = this.userAnswer === this.correctAnswer ? "回答正确!" : "回答错误!";
}
}
};
</script>
使用动态组件实现复杂填空题
对于更复杂的填空题场景(如多个填空或拖拽填空),可以使用动态组件或第三方库(如 vuedraggable)来实现。
<template>
<div>
<p>请将以下单词填入正确的位置:</p>
<div v-for="(item, index) in blanks" :key="index">
<p>{{ item.text }}</p>
<input v-model="item.userAnswer" placeholder="请输入答案" />
</div>
<button @click="checkAnswers">提交</button>
<p v-if="showResult">{{ result }}</p>
</div>
</template>
<script>
export default {
data() {
return {
blanks: [
{ text: "Vue 是一个 __ 框架", answer: "前端", userAnswer: "" },
{ text: "Vue 的核心是 __", answer: "响应式", userAnswer: "" }
],
showResult: false,
result: ""
};
},
methods: {
checkAnswers() {
const allCorrect = this.blanks.every(
item => item.userAnswer === item.answer
);
this.showResult = true;
this.result = allCorrect ? "全部回答正确!" : "有错误答案!";
}
}
};
</script>
以上方法可以根据实际需求灵活调整,适用于从简单到复杂的填空题场景。







