vue实现多选答题
实现多选答题功能
在Vue中实现多选答题功能,可以通过以下方法完成:
数据准备 定义一个questions数组,每个问题包含题目和选项,选项是一个对象数组,每个选项有文本和是否被选中的状态。
data() {
return {
questions: [
{
title: '问题1',
options: [
{ text: '选项A', selected: false },
{ text: '选项B', selected: false },
{ text: '选项C', selected: false }
]
}
]
}
}
模板渲染 使用v-for循环渲染问题和选项,每个选项绑定到checkbox的v-model。
<div v-for="(question, qIndex) in questions" :key="qIndex">
<h3>{{ question.title }}</h3>
<div v-for="(option, oIndex) in question.options" :key="oIndex">
<input
type="checkbox"
:id="`q${qIndex}-o${oIndex}`"
v-model="option.selected"
>
<label :for="`q${qIndex}-o${oIndex}`">{{ option.text }}</label>
</div>
</div>
提交处理 创建一个方法来收集用户选择的答案,遍历questions数组,找出所有被选中的选项。
methods: {
submitAnswers() {
const answers = this.questions.map(question => {
return question.options
.filter(opt => opt.selected)
.map(opt => opt.text)
})
console.log('用户答案:', answers)
// 这里可以添加提交到服务器的逻辑
}
}
样式增强 可以添加CSS样式来改善用户体验,比如选项间距、选中状态高亮等。
div.question {
margin-bottom: 20px;
}
div.option {
margin: 5px 0;
}
input[type="checkbox"] {
margin-right: 10px;
}
验证功能 添加验证逻辑确保至少选择了一个选项。
validateAnswers() {
return this.questions.every(question =>
question.options.some(opt => opt.selected)
)
}
完整组件示例
<template>
<div>
<div v-for="(question, qIndex) in questions" :key="qIndex" class="question">
<h3>{{ question.title }}</h3>
<div v-for="(option, oIndex) in question.options" :key="oIndex" class="option">
<input
type="checkbox"
:id="`q${qIndex}-o${oIndex}`"
v-model="option.selected"
>
<label :for="`q${qIndex}-o${oIndex}`">{{ option.text }}</label>
</div>
</div>
<button @click="submitAnswers">提交答案</button>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
{
title: '哪些是前端框架?',
options: [
{ text: 'Vue', selected: false },
{ text: 'React', selected: false },
{ text: 'Angular', selected: false },
{ text: 'jQuery', selected: false }
]
}
]
}
},
methods: {
submitAnswers() {
if (!this.validateAnswers()) {
alert('请至少选择一个选项')
return
}
const answers = this.questions.map(question => {
return question.options
.filter(opt => opt.selected)
.map(opt => opt.text)
})
console.log('用户答案:', answers)
},
validateAnswers() {
return this.questions.every(question =>
question.options.some(opt => opt.selected)
)
}
}
}
</script>
<style>
.question {
margin-bottom: 20px;
}
.option {
margin: 5px 0;
}
input[type="checkbox"] {
margin-right: 10px;
}
</style>
这种方法提供了完整的多选答题功能,包括数据管理、用户交互、答案收集和基本验证。可以根据实际需求进一步扩展,比如添加题目分页、计时功能或更复杂的验证逻辑。







