vue实现答题显示答案
实现答题显示答案的Vue方案
数据准备
创建包含题目和答案的数据结构,通常使用数组存储。每个题目对象包含问题、选项、正确答案等属性。
data() {
return {
questions: [
{
id: 1,
question: "Vue的核心特性是什么?",
options: ["组件化", "双向数据绑定", "虚拟DOM", "全部都是"],
answer: 3,
showAnswer: false
},
// 更多题目...
],
currentIndex: 0
}
}
显示题目逻辑
使用v-for或直接绑定当前题目数据到模板,控制答案显示状态。
<div v-for="(q, index) in questions" :key="q.id" v-show="index === currentIndex">
<h3>{{ q.question }}</h3>
<ul>
<li v-for="(option, i) in q.options" :key="i">
{{ option }}
</li>
</ul>
<button @click="toggleAnswer(q)">显示答案</button>
<div v-if="q.showAnswer">
正确答案: {{ q.options[q.answer] }}
</div>
</div>
切换答案可见性
通过方法控制showAnswer属性的切换,实现答案的显示/隐藏。
methods: {
toggleAnswer(question) {
question.showAnswer = !question.showAnswer
},
nextQuestion() {
if (this.currentIndex < this.questions.length - 1) {
this.currentIndex++
}
},
prevQuestion() {
if (this.currentIndex > 0) {
this.currentIndex--
}
}
}
样式优化
添加CSS样式提升交互体验,如答案区域的过渡效果。
.answer {
transition: all 0.3s ease;
background-color: #f5f5f5;
padding: 10px;
margin-top: 10px;
}
完整组件示例
整合以上代码形成可复用的答题组件。
<template>
<div class="quiz-container">
<div class="question-box">
<h3>{{ currentQuestion.question }}</h3>
<ul>
<li v-for="(option, index) in currentQuestion.options"
:key="index">
{{ option }}
</li>
</ul>
<button @click="showAnswer">显示答案</button>
<div v-if="currentQuestion.showAnswer" class="answer">
正确答案: {{ currentQuestion.options[currentQuestion.answer] }}
</div>
</div>
<div class="nav-buttons">
<button @click="prevQuestion" :disabled="currentIndex === 0">上一题</button>
<button @click="nextQuestion"
:disabled="currentIndex === questions.length - 1">
下一题
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
// 题目数据...
],
currentIndex: 0
}
},
computed: {
currentQuestion() {
return this.questions[this.currentIndex]
}
},
methods: {
// 方法实现...
}
}
</script>
高级功能扩展
可考虑添加以下增强功能:
- 用户答案记录和评分系统
- 答题计时功能
- 题目分类和筛选
- 本地存储答题进度
- 随机出题顺序
通过以上方案可以构建一个基础的答题显示答案功能,根据实际需求可进一步扩展和完善。核心思路是通过数据驱动视图,利用Vue的响应式特性管理答题状态。







