vue 实现答题功能
实现答题功能的基本思路
在Vue中实现答题功能,通常需要设计以下核心组件:题目展示、选项交互、答题状态管理、结果统计等。下面将分步骤说明具体实现方式。
数据结构设计
答题功能的基础是合理的数据结构。通常需要定义题目列表和用户答案存储对象。
data() {
return {
questions: [
{
id: 1,
title: "问题1",
options: ["选项A", "选项B", "选项C"],
answer: 0 // 正确答案索引
},
// 更多题目...
],
userAnswers: {}, // 存储用户答案 {题目id: 选择索引}
currentIndex: 0 // 当前题目索引
}
}
题目展示组件
创建题目展示组件,渲染当前题目和选项。
<template>
<div class="question-container">
<h3>{{ currentQuestion.title }}</h3>
<ul>
<li v-for="(option, index) in currentQuestion.options"
:key="index"
@click="selectAnswer(index)"
:class="{ selected: isSelected(index) }">
{{ option }}
</li>
</ul>
</div>
</template>
答案选择逻辑
实现选项选择和答案存储功能。
methods: {
selectAnswer(index) {
this.$set(this.userAnswers, this.currentQuestion.id, index)
},
isSelected(index) {
return this.userAnswers[this.currentQuestion.id] === index
}
},
computed: {
currentQuestion() {
return this.questions[this.currentIndex]
}
}
题目导航控制
添加题目切换按钮和进度控制。
<div class="navigation">
<button @click="prevQuestion" :disabled="currentIndex === 0">上一题</button>
<span>{{ currentIndex + 1 }}/{{ questions.length }}</span>
<button @click="nextQuestion" :disabled="currentIndex === questions.length - 1">下一题</button>
</div>
答题结果计算
实现提交功能并计算得分。

methods: {
submitAnswers() {
let score = 0
this.questions.forEach(q => {
if (this.userAnswers[q.id] === q.answer) {
score++
}
})
return {
total: this.questions.length,
correct: score,
percentage: (score / this.questions.length * 100).toFixed(2)
}
}
}
样式增强
添加基础样式提升用户体验。
.question-container li {
padding: 10px;
margin: 5px;
cursor: pointer;
border: 1px solid #ddd;
}
.question-container li.selected {
background-color: #e6f7ff;
border-color: #1890ff;
}
.navigation {
margin-top: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
进阶功能实现
对于更复杂的需求,可以考虑以下扩展:
计时功能
添加答题时间限制和计时器显示。

题目类型扩展
支持多选题、判断题等不同类型题目。
本地存储
使用localStorage保存答题进度,实现断点续答。
动画过渡
为题目切换添加过渡动画效果。
随机出题
实现题目随机排序功能。
通过以上步骤,可以构建一个基础的Vue答题功能,根据实际需求进行相应扩展和优化。






