vue实现单选多选答题
Vue 实现单选/多选答题功能
数据准备
定义题目和选项数据,通常在 data 或 setup 中声明。单选和多选的数据结构类似,但多选需要数组存储答案。
data() {
return {
questions: [
{
id: 1,
text: "单选题示例",
type: "single",
options: [
{ id: 1, text: "选项A" },
{ id: 2, text: "选项B" }
],
answer: null // 存储选中选项ID
},
{
id: 2,
text: "多选题示例",
type: "multiple",
options: [
{ id: 1, text: "选项A" },
{ id: 2, text: "选项B" }
],
answer: [] // 存储选中选项ID数组
}
]
}
}
模板渲染
使用 v-for 循环渲染题目和选项,通过 v-model 绑定选中状态。
<div v-for="question in questions" :key="question.id">
<h3>{{ question.text }}</h3>
<div v-if="question.type === 'single'">
<label v-for="option in question.options" :key="option.id">
<input
type="radio"
:name="'question-' + question.id"
:value="option.id"
v-model="question.answer"
>
{{ option.text }}
</label>
</div>
<div v-else>
<label v-for="option in question.options" :key="option.id">
<input
type="checkbox"
:value="option.id"
v-model="question.answer"
>
{{ option.text }}
</label>
</div>
</div>
答案提交
通过方法处理提交逻辑,验证答案格式(单选为单个值,多选为数组)。
methods: {
submitAnswers() {
const answers = this.questions.map(q => ({
questionId: q.id,
answer: q.answer
}));
console.log("提交的答案:", answers);
// 实际场景可调用API提交
}
}
样式优化
添加CSS增强交互体验,例如选中高亮效果。
label {
display: block;
padding: 8px;
margin: 4px 0;
cursor: pointer;
}
label:hover {
background-color: #f0f0f0;
}
input[type="radio"],
input[type="checkbox"] {
margin-right: 8px;
}
动态组件扩展
通过 component :is 实现题型切换,提升代码复用性。
<component
:is="question.type === 'single' ? 'RadioQuestion' : 'CheckboxQuestion'"
:question="question"
></component>
响应式验证
使用计算属性或 watch 监听答案变化,实时验证完整性。
computed: {
isAllAnswered() {
return this.questions.every(q =>
q.type === 'single'
? q.answer !== null
: q.answer.length > 0
);
}
}
通过以上步骤可实现完整的答题功能,支持单选和多选题型,具备数据绑定、提交验证和样式交互。实际开发中可根据需求扩展计时、题目切换等功能。







