vue实现考试多选功能
实现考试多选功能的方法
数据绑定与选项渲染
使用v-model绑定用户选择的答案数组,配合v-for渲染选项列表:
<template>
<div v-for="(option, index) in question.options" :key="index">
<input
type="checkbox"
:id="'option-' + index"
v-model="selectedAnswers"
:value="option.id"
>
<label :for="'option-' + index">{{ option.text }}</label>
</div>
</template>
<script>
export default {
data() {
return {
question: {
options: [
{ id: 1, text: "选项A" },
{ id: 2, text: "选项B" },
{ id: 3, text: "选项C" }
]
},
selectedAnswers: []
}
}
}
</script>
答案验证逻辑
添加方法验证是否至少选择了一个选项:
methods: {
validateSelection() {
if (this.selectedAnswers.length === 0) {
alert('请至少选择一个选项');
return false;
}
return true;
}
}
提交处理
在提交时处理多选结果:
methods: {
submitAnswers() {
if (!this.validateSelection()) return;
const result = {
questionId: this.question.id,
selectedOptionIds: this.selectedAnswers
};
// 提交到后端或存储
console.log(result);
}
}
样式优化
添加CSS增强用户体验:
input[type="checkbox"] {
margin-right: 8px;
}
label {
cursor: pointer;
user-select: none;
}
完整组件示例
<template>
<div class="multi-choice">
<h3>{{ question.text }}</h3>
<div
v-for="(option, index) in question.options"
:key="option.id"
class="option-item"
>
<input
type="checkbox"
:id="'option-' + index"
v-model="selectedAnswers"
:value="option.id"
>
<label :for="'option-' + index">{{ option.text }}</label>
</div>
<button @click="submitAnswers">提交</button>
</div>
</template>
<script>
export default {
props: {
question: {
type: Object,
required: true
}
},
data() {
return {
selectedAnswers: []
}
},
methods: {
submitAnswers() {
if (this.selectedAnswers.length === 0) {
alert('请至少选择一个选项');
return;
}
this.$emit('answered', this.selectedAnswers);
}
}
}
</script>
<style>
.multi-choice {
border: 1px solid #eee;
padding: 16px;
border-radius: 4px;
}
.option-item {
margin: 8px 0;
}
button {
margin-top: 12px;
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
注意事项
- 初始化时
selectedAnswers应为空数组 - 选项的
value应使用唯一标识符 - 父组件通过
props传递题目数据 - 使用
$emit将答案传递给父组件 - 移动端可考虑替换原生复选框为自定义样式






