vue实现多选答题

Vue 实现多选答题功能
实现多选答题功能需要结合 Vue 的数据绑定和事件处理机制,以下是一个完整的实现方案:
数据结构设计
data() {
return {
questions: [
{
id: 1,
text: "以下哪些是前端框架?",
options: [
{ id: 1, text: "Vue", selected: false },
{ id: 2, text: "React", selected: false },
{ id: 3, text: "Angular", selected: false },
{ id: 4, text: "jQuery", selected: false }
],
multiple: true
}
],
currentQuestionIndex: 0
}
}
模板渲染
<div v-for="(question, qIndex) in questions" :key="question.id">
<h3>{{ question.text }}</h3>
<div v-for="(option, oIndex) in question.options" :key="option.id">
<label>
<input
type="checkbox"
v-model="option.selected"
@change="handleOptionChange(question, option)"
>
{{ option.text }}
</label>
</div>
</div>
选项选择处理
methods: {
handleOptionChange(question, changedOption) {
if (!question.multiple) {
question.options.forEach(option => {
if (option.id !== changedOption.id) {
option.selected = false
}
})
}
}
}
答案提交验证
methods: {
submitAnswers() {
const selectedOptions = this.questions[this.currentQuestionIndex].options
.filter(opt => opt.selected)
.map(opt => opt.id)
if (selectedOptions.length === 0) {
alert("请至少选择一个选项")
return
}
// 处理提交逻辑
console.log("已选答案:", selectedOptions)
}
}
样式优化
.question-container {
margin-bottom: 20px;
}
.option-item {
margin: 10px 0;
display: flex;
align-items: center;
}
input[type="checkbox"] {
margin-right: 10px;
}
.submit-btn {
margin-top: 20px;
padding: 8px 16px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
完整组件示例
<template>
<div class="quiz-container">
<div v-for="(question, qIndex) in questions"
:key="question.id"
class="question-container">
<h3>{{ question.text }}</h3>
<div v-for="(option, oIndex) in question.options"
:key="option.id"
class="option-item">
<label>
<input
type="checkbox"
v-model="option.selected"
@change="handleOptionChange(question, option)"
>
{{ option.text }}
</label>
</div>
</div>
<button class="submit-btn" @click="submitAnswers">提交答案</button>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
{
id: 1,
text: "以下哪些是前端框架?",
options: [
{ id: 1, text: "Vue", selected: false },
{ id: 2, text: "React", selected: false },
{ id: 3, text: "Angular", selected: false },
{ id: 4, text: "jQuery", selected: false }
],
multiple: true
}
]
}
},
methods: {
handleOptionChange(question, changedOption) {
if (!question.multiple) {
question.options.forEach(option => {
if (option.id !== changedOption.id) {
option.selected = false
}
})
}
},
submitAnswers() {
const selectedOptions = this.questions[0].options
.filter(opt => opt.selected)
.map(opt => opt.id)
if (selectedOptions.length === 0) {
alert("请至少选择一个选项")
return
}
console.log("已选答案:", selectedOptions)
}
}
}
</script>
<style scoped>
/* 样式代码同上 */
</style>
这个实现方案包含了多选答题的核心功能,可以根据实际需求进行扩展,如添加更多题目、实现题目切换、添加计时功能等。







