vue实现考试多选功能
实现考试多选功能的核心逻辑
Vue中实现多选功能需要结合v-model和复选框(checkbox)的绑定,动态管理用户选择的选项。以下是一个完整的实现方案:
数据结构设计
使用数组存储题目和选项,每个选项包含id和text属性,通过v-for动态渲染。用户选择的答案通过数组存储。
data() {
return {
questions: [
{
id: 1,
text: "问题1",
options: [
{ id: 'A', text: '选项A' },
{ id: 'B', text: '选项B' },
{ id: 'C', text: '选项C' }
]
}
],
selectedAnswers: [] // 存储用户选择的选项ID(如['A', 'B'])
}
}
模板部分
使用v-model绑定到selectedAnswers数组,注意复选框的value需与选项ID一致。
<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.id"
:value="option.id"
v-model="selectedAnswers"
>
<label :for="option.id">{{ option.text }}</label>
</div>
</div>
处理提交逻辑
提交时验证用户选择,通过计算属性或方法处理结果。
methods: {
submitAnswers() {
if (this.selectedAnswers.length === 0) {
alert('请至少选择一个选项');
return;
}
console.log('用户选择:', this.selectedAnswers);
// 调用API提交答案
}
}
样式优化
添加CSS美化复选框,例如使用label的::before伪元素自定义样式:
input[type="checkbox"] {
opacity: 0;
position: absolute;
}
label::before {
content: '';
display: inline-block;
width: 16px;
height: 16px;
border: 1px solid #ddd;
margin-right: 8px;
}
input:checked + label::before {
background-color: #42b983;
}
动态禁用选项
若需要限制选择数量(如最多选2项),可通过:disabled动态控制:
<input
type="checkbox"
:disabled="selectedAnswers.length >= 2 && !selectedAnswers.includes(option.id)"
>
完整组件示例
整合后的单文件组件(SFC)结构:
<template>
<div class="exam-container">
<div v-for="question in questions" :key="question.id">
<h3>{{ question.text }}</h3>
<div class="options">
<div v-for="option in question.options" :key="option.id" class="option">
<input
type="checkbox"
:id="`q${question.id}_${option.id}`"
:value="option.id"
v-model="selectedAnswers"
>
<label :for="`q${question.id}_${option.id}`">{{ option.text }}</label>
</div>
</div>
</div>
<button @click="submitAnswers">提交答案</button>
</div>
</template>
<script>
export default {
data() {
return {
questions: [...], // 你的题目数据
selectedAnswers: []
}
},
methods: {
submitAnswers() {
// 提交逻辑
}
}
}
</script>
<style scoped>
/* 样式代码 */
</style>
关键注意事项
- 多选与单选的区别在于
v-model绑定到数组而非单个值 - 选项的
value必须唯一,通常使用ID或编码值 - 提交前需验证选择是否为空或超限
- 对于动态题目加载,需在
created或mounted钩子中初始化数据







