vue实现多选答题
vue实现多选答题
实现多选答题功能需要结合Vue的数据绑定和事件处理机制,通常包括题目展示、选项选择、提交验证等步骤。
数据结构设计
使用数组存储题目和选项,每个题目包含题干和选项列表,选项包含文本和是否选中状态。

data() {
return {
questions: [
{
id: 1,
text: "问题1",
options: [
{ id: 1, text: "选项A", selected: false },
{ id: 2, text: "选项B", selected: false }
]
}
]
}
}
选项选择处理
通过v-model绑定选项的selected属性,使用复选框实现多选。
<div v-for="question in questions" :key="question.id">
<h3>{{ question.text }}</h3>
<div v-for="option in question.options" :key="option.id">
<input
type="checkbox"
:id="`option-${option.id}`"
v-model="option.selected"
>
<label :for="`option-${option.id}`">{{ option.text }}</label>
</div>
</div>
提交验证
遍历题目和选项,检查是否有选中项并收集结果。

methods: {
submitAnswers() {
const answers = this.questions.map(question => {
return {
questionId: question.id,
selectedOptions: question.options
.filter(opt => opt.selected)
.map(opt => opt.id)
}
})
console.log(answers)
}
}
样式优化
添加CSS美化复选框和布局,提升用户体验。
input[type="checkbox"] {
margin-right: 8px;
}
.question {
margin-bottom: 20px;
}
完整组件示例
将上述代码整合为完整组件,包含数据、模板和方法。
<template>
<div class="quiz">
<div v-for="question in questions" :key="question.id" class="question">
<h3>{{ question.text }}</h3>
<div v-for="option in question.options" :key="option.id" class="option">
<input
type="checkbox"
:id="`option-${option.id}`"
v-model="option.selected"
>
<label :for="`option-${option.id}`">{{ option.text }}</label>
</div>
</div>
<button @click="submitAnswers">提交答案</button>
</div>
</template>






