vue实现答题
Vue 实现答题功能
实现答题功能通常需要以下几个关键步骤:
数据准备
- 准备题目数据,通常是一个数组,每个元素包含题目、选项、正确答案等信息。
- 示例数据结构:
questions: [ { id: 1, title: "Vue是什么?", options: ["前端框架", "后端语言", "数据库", "操作系统"], answer: 0 }, // 更多题目... ]
组件结构
- 创建答题组件,包含题目展示区、选项列表、提交按钮等。
- 使用v-for指令循环渲染题目和选项。
- 使用v-model绑定用户选择的答案。
状态管理
- 使用data属性存储当前题目索引、用户答案、得分等信息。
- 示例状态:
data() { return { currentIndex: 0, userAnswers: [], score: 0, showResult: false } }
答题逻辑
- 实现题目切换方法,处理上一题/下一题逻辑。
- 实现答案校验方法,对比用户答案和正确答案。
- 计算得分并显示结果。
样式设计
- 使用CSS美化答题界面,突出显示当前题目。
- 添加选中状态样式,反馈用户选择。
- 设计结果展示样式。
完整示例代码
<template>
<div class="quiz-container">
<div v-if="!showResult">
<h3>{{ questions[currentIndex].title }}</h3>
<ul>
<li v-for="(option, index) in questions[currentIndex].options"
:key="index"
@click="selectAnswer(index)"
:class="{ selected: userAnswers[currentIndex] === index }">
{{ option }}
</li>
</ul>
<button @click="prevQuestion" :disabled="currentIndex === 0">上一题</button>
<button @click="nextQuestion">下一题</button>
</div>
<div v-else>
<h3>答题结果</h3>
<p>得分: {{ score }}/{{ questions.length }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
{
id: 1,
title: "Vue是什么?",
options: ["前端框架", "后端语言", "数据库", "操作系统"],
answer: 0
},
// 更多题目...
],
currentIndex: 0,
userAnswers: [],
score: 0,
showResult: false
}
},
methods: {
selectAnswer(index) {
this.$set(this.userAnswers, this.currentIndex, index)
},
prevQuestion() {
if (this.currentIndex > 0) {
this.currentIndex--
}
},
nextQuestion() {
if (this.currentIndex < this.questions.length - 1) {
this.currentIndex++
} else {
this.calculateScore()
this.showResult = true
}
},
calculateScore() {
this.score = this.questions.reduce((acc, question, index) => {
return acc + (question.answer === this.userAnswers[index] ? 1 : 0)
}, 0)
}
}
}
</script>
<style>
.selected {
background-color: #42b983;
color: white;
}
</style>
功能扩展建议
- 添加计时功能,限制答题时间
- 实现题目随机排序
- 添加答题进度显示
- 支持多种题型(单选、多选、判断等)
- 使用Vuex管理全局状态
- 添加动画过渡效果
注意事项

- 确保题目数据的完整性和正确性
- 处理边界情况,如最后一题和第一题的切换
- 考虑移动端适配
- 添加适当的用户反馈,如回答正确/错误的提示






