vue实现答题组件
Vue 实现答题组件
数据结构设计
使用数组存储题目数据,每个题目对象包含问题、选项、正确答案等字段:
data() {
return {
questions: [
{
id: 1,
text: "Vue的核心特性是什么?",
options: ["组件化", "双向数据绑定", "虚拟DOM", "全部"],
answer: 3
}
],
currentIndex: 0,
selectedOption: null
}
}
模板渲染
通过v-for渲染题目和选项,使用v-model绑定用户选择:
<template>
<div class="quiz-container">
<h3>{{ questions[currentIndex].text }}</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>
</div>
</template>
交互逻辑
实现答案验证和题目切换功能:
methods: {
submitAnswer() {
const isCorrect = this.selectedOption === this.questions[this.currentIndex].answer
alert(isCorrect ? '回答正确' : '回答错误')
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;
}
button {
margin-top: 20px;
padding: 8px 16px;
}
进阶功能实现
-
添加计时器组件
data() { return { timeLeft: 30, timer: null } }, mounted() { this.timer = setInterval(() => { if(this.timeLeft > 0) { this.timeLeft-- } else { clearInterval(this.timer) alert('时间到!') } }, 1000) } -
实现分数统计
data() { return { score: 0 } }, methods: { submitAnswer() { if(this.selectedOption === this.questions[this.currentIndex].answer) { this.score += 10 } // 其他逻辑... } } -
添加题目进度显示
<div class="progress"> 第 {{ currentIndex + 1 }} 题/共 {{ questions.length }} 题 </div>







