vue实现答题组件
Vue 实现答题组件
数据准备
定义一个包含题目、选项和正确答案的数据结构。通常使用数组存储题目列表,每个题目对象包含题目内容、选项数组和正确答案索引。
data() {
return {
questions: [
{
question: "Vue.js 是什么?",
options: ["前端框架", "编程语言", "数据库", "操作系统"],
answer: 0
},
// 更多题目...
],
currentIndex: 0,
selectedOption: null,
score: 0
}
}
组件模板
创建答题界面模板,显示当前题目、选项列表和导航按钮。使用 v-for 渲染选项列表,v-model 绑定用户选择。

<template>
<div class="quiz-container">
<h3>{{ questions[currentIndex].question }}</h3>
<ul>
<li v-for="(option, index) in questions[currentIndex].options" :key="index">
<input
type="radio"
:id="'option-' + index"
:value="index"
v-model="selectedOption"
>
<label :for="'option-' + index">{{ option }}</label>
</li>
</ul>
<button @click="submitAnswer">提交</button>
<button @click="nextQuestion" :disabled="currentIndex >= questions.length - 1">
下一题
</button>
</div>
</template>
逻辑实现
实现答题验证和题目切换逻辑。提交答案时检查是否正确并更新分数,切换题目时重置选择状态。
methods: {
submitAnswer() {
if (this.selectedOption === this.questions[this.currentIndex].answer) {
this.score++
alert("回答正确!")
} else {
alert("回答错误!")
}
},
nextQuestion() {
if (this.currentIndex < this.questions.length - 1) {
this.currentIndex++
this.selectedOption = null
}
}
}
样式优化
添加基础样式提升用户体验,包括选项高亮、按钮状态和布局调整。

.quiz-container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 10px 0;
padding: 10px;
border: 1px solid #eee;
cursor: pointer;
}
li:hover {
background-color: #f5f5f5;
}
button {
margin: 10px 5px;
padding: 8px 16px;
}
进度显示
添加进度条或文字提示显示当前答题进度,帮助用户了解整体情况。
<div class="progress">
题目 {{ currentIndex + 1 }} / {{ questions.length }}
</div>
结果统计
在最后一道题完成后显示总分和答题情况总结。
computed: {
isQuizFinished() {
return this.currentIndex === this.questions.length - 1
}
}
<div v-if="isQuizFinished" class="result">
<h3>测试完成!</h3>
<p>你的得分: {{ score }} / {{ questions.length }}</p>
</div>






