vue 实现答题功能
Vue 实现答题功能的方法
数据结构和状态管理
使用 Vue 的 data 或 ref(Composition API)存储题目列表和用户答案。例如:

data() {
return {
questions: [
{ id: 1, text: "问题1", options: ["A", "B", "C"], correct: 0 },
{ id: 2, text: "问题2", options: ["A", "B"], correct: 1 }
],
userAnswers: {}
}
}
动态渲染题目
通过 v-for 循环渲染题目和选项,使用 v-model 绑定用户选择:

<div v-for="q in questions" :key="q.id">
<h3>{{ q.text }}</h3>
<div v-for="(opt, index) in q.options" :key="index">
<input
type="radio"
:id="`q${q.id}_opt${index}`"
:value="index"
v-model="userAnswers[q.id]"
>
<label :for="`q${q.id}_opt${index}`">{{ opt }}</label>
</div>
</div>
提交与验证逻辑
计算得分时遍历用户答案并与正确答案对比:
methods: {
calculateScore() {
return this.questions.reduce((score, q) => {
return score + (this.userAnswers[q.id] === q.correct ? 1 : 0)
}, 0)
}
}
进度和结果展示
显示当前题号、总题数和最终结果:
<div>进度: {{ Object.keys(userAnswers).length }}/{{ questions.length }}</div>
<button @click="calculateScore">提交答案</button>
<div v-if="score !== null">得分: {{ score }}/{{ questions.length }}</div>
高级功能扩展
- 题型支持:通过
question.type字段区分单选、多选、填空等题型 - 状态持久化:使用
localStorage保存答题进度 - 动画效果:通过 Vue 的
<transition>添加题目切换动画 - API 集成:使用
axios动态加载题目数据
完整示例(Composition API)
<script setup>
import { ref } from 'vue'
const questions = ref([
// 题目数据
])
const userAnswers = ref({})
const score = ref(null)
const submit = () => {
score.value = questions.value.reduce((total, q) => {
return total + (userAnswers.value[q.id] === q.correct ? 1 : 0)
}, 0)
}
</script>






