vue实现单选答题功能
实现单选答题功能的基本思路
在Vue中实现单选答题功能,可以通过v-model绑定选项值,结合v-for渲染选项列表,并监听选择事件。以下是一个完整的实现示例。
创建答题组件
新建一个Vue单文件组件(如SingleChoice.vue),包含题目、选项列表和提交逻辑。
<template>
<div class="single-choice">
<h3>{{ question.title }}</h3>
<ul>
<li v-for="(option, index) in question.options" :key="index">
<input
type="radio"
:id="'option-' + index"
:value="option.value"
v-model="selectedOption"
/>
<label :for="'option-' + index">{{ option.text }}</label>
</li>
</ul>
<button @click="submitAnswer" :disabled="!selectedOption">提交</button>
<p v-if="feedback">{{ feedback }}</p>
</div>
</template>
定义组件数据与逻辑
在<script>部分定义题目数据、选择状态和提交逻辑。
<script>
export default {
data() {
return {
question: {
title: "以下哪个是Vue的核心特性?",
options: [
{ text: "双向数据绑定", value: "a" },
{ text: "虚拟DOM", value: "b" },
{ text: "组件化", value: "c" },
{ text: "以上都是", value: "d" }
],
correctAnswer: "d"
},
selectedOption: null,
feedback: ""
};
},
methods: {
submitAnswer() {
if (this.selectedOption === this.question.correctAnswer) {
this.feedback = "回答正确!";
} else {
this.feedback = "回答错误,请再试一次。";
}
}
}
};
</script>
添加样式增强交互
在<style>部分添加基础样式,提升用户体验。
<style scoped>
.single-choice {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 10px 0;
}
button {
margin-top: 15px;
padding: 8px 16px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
}
button:disabled {
background-color: #cccccc;
}
</style>
动态加载题目数据
如需从后端API获取题目,可在created生命周期钩子中发起请求。
created() {
fetch('/api/questions/1')
.then(response => response.json())
.then(data => {
this.question = data;
});
}
处理多题目场景
对于多题目切换,可以在父组件中维护题目列表和当前索引。
// 父组件
data() {
return {
questions: [...], // 题目数组
currentIndex: 0
};
},
methods: {
nextQuestion() {
if (this.currentIndex < this.questions.length - 1) {
this.currentIndex++;
}
}
}
<!-- 父组件模板 -->
<single-choice :question="questions[currentIndex]" @answered="nextQuestion" />
注意事项
- 确保每个radio的
id属性唯一,避免点击冲突 - 使用
v-model时,绑定的数据初始值应为null而非空字符串 - 对于无障碍访问,建议为选项添加
aria-label描述 - 复杂场景可考虑使用Vuex管理答题状态
以上实现涵盖了单选答题的核心功能,可根据实际需求扩展验证逻辑、动画效果或积分系统。







