vue实现答题测评
Vue实现答题测评功能
数据准备
创建一个questions数组存储题目信息,每个题目对象包含问题文本、选项数组和正确答案。使用Vue的data属性或Pinia/Vuex状态管理存储当前题目索引、用户答案和得分。
data() {
return {
questions: [
{
question: "Vue的核心特性是什么?",
options: ["组件化", "双向绑定", "虚拟DOM", "以上都是"],
answer: 3
},
// 更多题目...
],
currentIndex: 0,
userAnswers: [],
score: 0
}
}
界面渲染
使用v-for指令渲染题目和选项,通过v-model绑定用户选择。动态显示当前题号和总题数,使用v-show或v-if控制题目切换。

<div class="question-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="userAnswers[currentIndex]"
>
<label :for="'option'+index">{{ option }}</label>
</li>
</ul>
<p>题目 {{ currentIndex + 1 }}/{{ questions.length }}</p>
</div>
功能逻辑
实现上一题、下一题和提交功能的方法。在切换题目时检查答案并计算得分,提交时显示最终结果。

methods: {
nextQuestion() {
if (this.userAnswers[this.currentIndex] === this.questions[this.currentIndex].answer) {
this.score++
}
if (this.currentIndex < this.questions.length - 1) {
this.currentIndex++
}
},
prevQuestion() {
if (this.currentIndex > 0) {
this.currentIndex--
}
},
submitQuiz() {
const unanswered = this.questions.length - this.userAnswers.length
alert(`测验完成!得分: ${this.score}/${this.questions.length},未作答: ${unanswered}`)
}
}
样式优化
添加CSS美化界面,使用过渡效果增强用户体验。可以添加进度条显示答题进度,对正确/错误答案提供视觉反馈。
.question-container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
border: 1px solid #eee;
border-radius: 8px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 10px 0;
padding: 10px;
background: #f5f5f5;
border-radius: 4px;
}
button {
margin: 10px 5px;
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
进阶功能
添加计时功能限制答题时间,实现题目随机排序,支持多种题型(多选题、判断题)。使用本地存储保存用户进度,允许中断后继续答题。
// 计时功能示例
data() {
return {
timeLeft: 60,
timer: null
}
},
mounted() {
this.timer = setInterval(() => {
if (this.timeLeft > 0) {
this.timeLeft--
} else {
clearInterval(this.timer)
this.submitQuiz()
}
}, 1000)
},
beforeUnmount() {
clearInterval(this.timer)
}






