vue做题功能实现
实现 Vue 做题功能的基本思路
Vue 可以实现一个完整的做题功能,包括题目展示、选项选择、答案提交和结果反馈。需要结合 Vue 的数据绑定、组件化和事件处理机制。
数据结构和状态管理
使用 Vue 的 data 或 ref(Composition API)来管理题目数据、用户答案和答题状态。
// Options API
data() {
return {
questions: [
{
id: 1,
text: 'Vue 是什么?',
options: ['框架', '库', '语言', '工具'],
answer: 0
}
],
currentQuestionIndex: 0,
userAnswers: []
}
}
// Composition API
const questions = ref([
{
id: 1,
text: 'Vue 是什么?',
options: ['框架', '库', '语言', '工具'],
answer: 0
}
]);
const currentQuestionIndex = ref(0);
const userAnswers = ref([]);
题目展示组件
创建一个组件来展示题目和选项,使用 v-for 渲染选项列表。
<template>
<div class="question-container">
<h3>{{ currentQuestion.text }}</h3>
<ul>
<li
v-for="(option, index) in currentQuestion.options"
:key="index"
@click="selectAnswer(index)"
:class="{ selected: userAnswers[currentQuestionIndex] === index }"
>
{{ option }}
</li>
</ul>
</div>
</template>
答案选择和提交
处理用户选择答案的逻辑,并更新用户答案数组。
methods: {
selectAnswer(index) {
this.userAnswers[this.currentQuestionIndex] = index;
},
submitAnswer() {
if (this.userAnswers[this.currentQuestionIndex] === undefined) {
alert('请选择一个答案');
return;
}
this.currentQuestionIndex++;
}
}
结果反馈和评分
在所有题目完成后,计算用户得分并提供反馈。

computed: {
score() {
return this.userAnswers.reduce((acc, answer, index) => {
return acc + (answer === this.questions[index].answer ? 1 : 0);
}, 0);
},
isFinished() {
return this.currentQuestionIndex >= this.questions.length;
}
}
完整示例代码
<template>
<div>
<div v-if="!isFinished">
<h3>{{ currentQuestion.text }}</h3>
<ul>
<li
v-for="(option, index) in currentQuestion.options"
:key="index"
@click="selectAnswer(index)"
:class="{ selected: userAnswers[currentQuestionIndex] === index }"
>
{{ option }}
</li>
</ul>
<button @click="submitAnswer">提交</button>
</div>
<div v-else>
<h3>测试完成!</h3>
<p>你的得分: {{ score }}/{{ questions.length }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
{
id: 1,
text: 'Vue 是什么?',
options: ['框架', '库', '语言', '工具'],
answer: 0
},
{
id: 2,
text: 'Vue 的核心特性是什么?',
options: ['响应式', '模板', '组件', '全部'],
answer: 3
}
],
currentQuestionIndex: 0,
userAnswers: []
}
},
computed: {
currentQuestion() {
return this.questions[this.currentQuestionIndex];
},
score() {
return this.userAnswers.reduce((acc, answer, index) => {
return acc + (answer === this.questions[index].answer ? 1 : 0);
}, 0);
},
isFinished() {
return this.currentQuestionIndex >= this.questions.length;
}
},
methods: {
selectAnswer(index) {
this.userAnswers[this.currentQuestionIndex] = index;
},
submitAnswer() {
if (this.userAnswers[this.currentQuestionIndex] === undefined) {
alert('请选择一个答案');
return;
}
this.currentQuestionIndex++;
}
}
}
</script>
<style>
.selected {
background-color: #eee;
}
</style>
进阶功能建议
- 计时功能:添加答题时间限制或计时器显示
- 题目分类:按难度或主题分类题目
- 持久化存储:使用 localStorage 保存用户进度和成绩
- 动画效果:添加题目切换时的过渡动画
- API 集成:从后端 API 获取题目数据
注意事项
- 确保题目数据结构一致,包含必要的字段(id, text, options, answer)
- 处理边界情况,如没有更多题目时的显示
- 考虑添加题目导航功能,允许用户跳转到特定题目
- 对于大型应用,考虑使用 Vuex 或 Pinia 进行状态管理






