vue实现单选多选答题
Vue实现单选答题
创建单选答题组件需要绑定v-model到同一个变量,确保同一时间只能选中一个选项。以下是一个基础实现示例:
<template>
<div>
<h3>单选题</h3>
<div v-for="(option, index) in options" :key="index">
<input
type="radio"
:id="'option' + index"
:value="option.value"
v-model="selectedAnswer"
>
<label :for="'option' + index">{{ option.text }}</label>
</div>
<p>当前选择: {{ selectedAnswer }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedAnswer: null,
options: [
{ text: "选项A", value: "A" },
{ text: "选项B", value: "B" },
{ text: "选项C", value: "C" }
]
}
}
}
</script>
Vue实现多选答题
多选答题需要绑定到数组类型变量,并使用v-model配合checkbox类型输入框:

<template>
<div>
<h3>多选题</h3>
<div v-for="(option, index) in options" :key="index">
<input
type="checkbox"
:id="'option' + index"
:value="option.value"
v-model="selectedAnswers"
>
<label :for="'option' + index">{{ option.text }}</label>
</div>
<p>当前选择: {{ selectedAnswers }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedAnswers: [],
options: [
{ text: "选项A", value: "A" },
{ text: "选项B", value: "B" },
{ text: "选项C", value: "C" }
]
}
}
}
</script>
动态题目加载
从API获取题目数据时,可以这样处理:
export default {
data() {
return {
questions: [],
currentQuestionIndex: 0,
answers: {}
}
},
async created() {
const response = await fetch('/api/questions')
this.questions = await response.json()
},
methods: {
goToNextQuestion() {
if (this.currentQuestionIndex < this.questions.length - 1) {
this.currentQuestionIndex++
}
}
}
}
表单验证与提交
添加验证逻辑和提交功能:

<template>
<form @submit.prevent="submitAnswers">
<!-- 单选或多选题组件 -->
<button type="submit" :disabled="!isFormValid">提交答案</button>
</form>
</template>
<script>
export default {
computed: {
isFormValid() {
return this.selectedAnswer !== null // 单选验证
// 或多选验证 return this.selectedAnswers.length > 0
}
},
methods: {
submitAnswers() {
// 提交逻辑
}
}
}
</script>
使用第三方UI库
使用Element UI实现更美观的界面:
<template>
<el-radio-group v-model="selectedAnswer">
<el-radio
v-for="(option, index) in options"
:key="index"
:label="option.value"
>
{{ option.text }}
</el-radio>
</el-radio-group>
<el-checkbox-group v-model="selectedAnswers">
<el-checkbox
v-for="(option, index) in options"
:key="index"
:label="option.value"
>
{{ option.text }}
</el-checkbox>
</el-checkbox-group>
</template>
状态管理
对于复杂应用,建议使用Vuex管理答题状态:
// store.js
export default new Vuex.Store({
state: {
answers: {}
},
mutations: {
setAnswer(state, { questionId, answer }) {
state.answers[questionId] = answer
}
}
})





