vue实现答题切换
实现答题切换的基本思路
在Vue中实现答题切换功能,通常需要管理当前题目索引、题目数据列表以及用户答案存储。通过绑定数据与视图,利用Vue的响应式特性实现题目切换时的自动更新。
核心代码实现
1. 定义数据结构和状态

data() {
return {
questions: [
{ id: 1, text: "问题1", options: ["A", "B", "C"] },
{ id: 2, text: "问题2", options: ["A", "B", "C"] }
],
currentIndex: 0,
answers: {}
}
}
2. 题目切换方法
methods: {
nextQuestion() {
if (this.currentIndex < this.questions.length - 1) {
this.currentIndex++
}
},
prevQuestion() {
if (this.currentIndex > 0) {
this.currentIndex--
}
}
}
3. 模板部分

<div class="quiz-container">
<div class="question">
<h3>{{ questions[currentIndex].text }}</h3>
<div v-for="(option, index) in questions[currentIndex].options" :key="index">
<input
type="radio"
:id="'q'+currentIndex+'o'+index"
:value="option"
v-model="answers[currentIndex]">
<label :for="'q'+currentIndex+'o'+index">{{ option }}</label>
</div>
</div>
<button @click="prevQuestion" :disabled="currentIndex === 0">上一题</button>
<button @click="nextQuestion" :disabled="currentIndex === questions.length - 1">下一题</button>
</div>
进阶功能实现
进度指示器
<div class="progress">
<span v-for="(q, index) in questions"
:key="q.id"
:class="{ active: index === currentIndex, answered: answers[index] }"
@click="currentIndex = index">
{{ index + 1 }}
</span>
</div>
答题结果提交
methods: {
submitAnswers() {
const unanswered = this.questions.filter((q, index) => !this.answers[index])
if (unanswered.length > 0) {
alert(`还有${unanswered.length}题未完成`)
} else {
// 提交逻辑
console.log(this.answers)
}
}
}
样式优化建议
.quiz-container {
max-width: 600px;
margin: 0 auto;
}
.question {
margin-bottom: 20px;
}
.progress span {
display: inline-block;
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
margin-right: 5px;
border-radius: 50%;
cursor: pointer;
}
.progress span.active {
background-color: #42b983;
color: white;
}
.progress span.answered {
background-color: #f0f0f0;
}
注意事项
- 使用Vue的响应式特性确保视图与数据同步
- 考虑添加过渡动画提升用户体验
- 对于大量题目可考虑分页或虚拟滚动优化性能
- 答题状态应持久化,避免页面刷新丢失进度






