vue答题功能实现
Vue 答题功能实现
数据结构设计
使用 Vue 的响应式数据管理题目和答案。通常需要一个数组存储题目列表,每个题目包含题干、选项、正确答案等字段。

data() {
return {
questions: [
{
id: 1,
title: "Vue 的核心特性是什么?",
options: ["组件化", "双向数据绑定", "虚拟DOM", "全部"],
answer: 3 // 正确答案索引
},
// 更多题目...
],
currentIndex: 0, // 当前题目索引
selectedAnswer: null, // 用户选择的答案
score: 0 // 得分
}
}
题目展示组件
通过计算属性获取当前题目,使用 v-for 渲染选项列表。

<template>
<div v-if="currentQuestion">
<h3>{{ currentQuestion.title }}</h3>
<ul>
<li
v-for="(option, index) in currentQuestion.options"
:key="index"
@click="selectAnswer(index)"
:class="{ 'selected': selectedAnswer === index }"
>
{{ option }}
</li>
</ul>
<button @click="submitAnswer">提交答案</button>
</div>
</template>
答案选择逻辑
实现答案选择和提交的逻辑,包括验证答案和计分功能。
methods: {
selectAnswer(index) {
this.selectedAnswer = index;
},
submitAnswer() {
if (this.selectedAnswer === null) return;
const isCorrect = this.selectedAnswer === this.currentQuestion.answer;
if (isCorrect) this.score++;
// 进入下一题或结束
if (this.currentIndex < this.questions.length - 1) {
this.currentIndex++;
this.selectedAnswer = null;
} else {
alert(`测试结束,得分: ${this.score}/${this.questions.length}`);
}
}
},
computed: {
currentQuestion() {
return this.questions[this.currentIndex];
}
}
状态样式反馈
通过动态 class 实现选中状态的视觉反馈。
li.selected {
background-color: #42b983;
color: white;
}
进阶功能
- 计时功能:使用
setInterval实现答题倒计时 - 题目分类:添加分类标签实现按类别筛选
- 结果分析:答题后显示错题解析
- 持久化存储:通过
localStorage保存答题进度
// 计时器示例
data() {
return {
timeLeft: 30
}
},
mounted() {
this.timer = setInterval(() => {
if (this.timeLeft > 0) this.timeLeft--;
else this.submitAnswer();
}, 1000);
},
beforeDestroy() {
clearInterval(this.timer);
}






