vue实现答题组件
Vue 实现答题组件的方法
基本结构设计
使用 Vue 的单文件组件(SFC)结构,包含模板、脚本和样式三部分。模板部分定义题目、选项和提交按钮,脚本部分处理逻辑,样式部分美化界面。
<template>
<div class="quiz-container">
<h3>{{ currentQuestion.title }}</h3>
<ul>
<li v-for="(option, index) in currentQuestion.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>
</div>
</template>
数据与状态管理
在 data 中定义题目列表、当前题目索引和用户选择的答案。通过计算属性动态获取当前题目。
<script>
export default {
data() {
return {
questions: [
{
title: "问题1:Vue 的核心特性是什么?",
options: ["响应式数据", "虚拟DOM", "双向绑定", "组件化"],
answer: 0
},
// 更多题目...
],
currentIndex: 0,
selectedOption: null
};
},
computed: {
currentQuestion() {
return this.questions[this.currentIndex];
}
}
};
</script>
逻辑实现
实现答案提交和题目切换逻辑。验证答案后更新分数或跳转到下一题。
methods: {
submitAnswer() {
if (this.selectedOption === null) return;
const isCorrect = this.selectedOption === this.currentQuestion.answer;
alert(isCorrect ? "回答正确!" : "回答错误!");
this.currentIndex++;
this.selectedOption = null;
}
}
样式优化
使用 CSS 美化组件,确保选项和按钮的交互体验良好。
<style scoped>
.quiz-container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 10px 0;
}
button {
margin-top: 20px;
padding: 10px 20px;
background: #42b983;
color: white;
border: none;
cursor: pointer;
}
</style>
进阶功能扩展
- 计时功能:通过
setInterval实现答题倒计时。 - 结果统计:在组件销毁前汇总正确率。
- 动态加载题目:通过 API 异步获取题目数据。
// 计时功能示例
data() {
return {
timeLeft: 30
};
},
mounted() {
this.timer = setInterval(() => {
if (this.timeLeft > 0) this.timeLeft--;
else this.submitAnswer();
}, 1000);
},
beforeDestroy() {
clearInterval(this.timer);
}
组件复用与封装
通过 props 接收外部传入的题目数据,提升组件复用性。

props: {
questions: {
type: Array,
required: true
}
}
注意事项
- 使用
v-model绑定单选按钮时,确保选项的值唯一。 - 题目切换时重置
selectedOption避免状态残留。 - 样式添加
scoped避免污染全局 CSS。






