vue实现答题
Vue 实现答题功能
数据结构设计
使用 Vue 的响应式特性管理题目和答案数据。通常需要以下数据结构:
data() {
return {
questions: [
{
id: 1,
text: "问题1内容",
options: ["选项A", "选项B", "选项C"],
correctAnswer: 0 // 正确答案索引
}
],
currentQuestionIndex: 0,
userAnswers: [],
showResult: false
}
}
动态渲染题目
通过 v-for 指令循环渲染题目和选项:

<div v-for="(question, index) in questions" :key="question.id" v-show="index === currentQuestionIndex">
<h3>{{ question.text }}</h3>
<ul>
<li v-for="(option, optionIndex) in question.options" :key="optionIndex">
<input
type="radio"
:id="'q'+index+'-opt'+optionIndex"
:value="optionIndex"
v-model="userAnswers[index]"
>
<label :for="'q'+index+'-opt'+optionIndex">{{ option }}</label>
</li>
</ul>
</div>
导航控制
实现题目切换和提交功能:

methods: {
nextQuestion() {
if (this.currentQuestionIndex < this.questions.length - 1) {
this.currentQuestionIndex++
}
},
prevQuestion() {
if (this.currentQuestionIndex > 0) {
this.currentQuestionIndex--
}
},
submitAnswers() {
this.showResult = true
}
}
结果计算
计算得分和显示结果:
computed: {
score() {
return this.userAnswers.reduce((acc, answer, index) => {
return answer === this.questions[index].correctAnswer ? acc + 1 : acc
}, 0)
}
}
样式优化
添加过渡效果提升用户体验:
.question-enter-active, .question-leave-active {
transition: opacity 0.5s ease;
}
.question-enter, .question-leave-to {
opacity: 0;
}
进阶功能
- 计时器功能:使用 setInterval 实现答题倒计时
- 题目随机排序:提交前打乱题目顺序
- 保存进度:使用 localStorage 保存答题状态
- 题目分类:按难度或类型分组显示
实现答题系统时,应确保组件结构清晰,将题目显示、导航控制和结果展示拆分为独立组件,通过 props 和 events 进行通信。对于大型应用,可以考虑使用 Vuex 进行状态管理。






