vue实现考试多选功能
Vue实现考试多选功能
数据绑定与选项渲染
使用v-model绑定用户选择的答案数组,结合v-for循环渲染选项列表。示例代码:
<template>
<div>
<h3>{{ question.title }}</h3>
<div v-for="(option, index) in question.options" :key="index">
<input
type="checkbox"
:id="'option-' + index"
:value="option.value"
v-model="selectedAnswers"
>
<label :for="'option-' + index">{{ option.text }}</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
question: {
title: "多选题示例",
options: [
{ value: "A", text: "选项A" },
{value: "B", text: "选项B" },
{value: "C", text: "选项C" }
]
},
selectedAnswers: []
}
}
}
</script>
选项验证逻辑
添加验证逻辑确保至少选择N个选项。在methods中添加验证方法:

methods: {
validateSelection() {
if (this.selectedAnswers.length < 2) {
alert("请至少选择两个选项");
return false;
}
return true;
}
}
结果提交处理
通过计算属性处理已选答案,提交时进行格式转换:

computed: {
formattedAnswers() {
return this.selectedAnswers.join(",");
}
},
methods: {
submitAnswers() {
if (!this.validateSelection()) return;
console.log("提交答案:", this.formattedAnswers);
// 实际提交逻辑
}
}
样式优化
为选中状态添加视觉反馈,CSS示例:
input[type="checkbox"]:checked + label {
color: #42b983;
font-weight: bold;
}
完整组件示例
整合所有功能的完整组件代码:
<template>
<div class="multi-choice">
<h3>{{ question.title }}</h3>
<div class="options">
<div
v-for="(option, index) in question.options"
:key="index"
class="option-item"
>
<input
type="checkbox"
:id="'option-' + index"
:value="option.value"
v-model="selectedAnswers"
>
<label :for="'option-' + index">{{ option.text }}</label>
</div>
</div>
<button @click="submitAnswers">提交答案</button>
</div>
</template>
<script>
export default {
data() {
return {
question: {
title: "请选择正确的选项(多选)",
options: [
{ value: "A", text: "选项A" },
{ value: "B", text: "选项B" },
{ value: "C", text: "选项C" },
{ value: "D", text: "选项D" }
]
},
selectedAnswers: []
};
},
methods: {
validateSelection() {
return this.selectedAnswers.length >= 2;
},
submitAnswers() {
if (!this.validateSelection()) {
alert("请至少选择两个选项");
return;
}
console.log("提交的答案:", this.selectedAnswers);
}
}
};
</script>
<style>
.multi-choice {
max-width: 600px;
margin: 0 auto;
}
.option-item {
margin: 10px 0;
padding: 8px;
border: 1px solid #eee;
}
input[type="checkbox"] {
margin-right: 10px;
}
button {
margin-top: 20px;
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
}
</style>






