vue实现答题
Vue实现答题功能
在Vue中实现答题功能,可以采用组件化开发方式,结合状态管理(如Vuex或Pinia)来处理答题逻辑和数据流转。以下是一个典型的实现方案:
数据结构设计
使用数组存储题目信息,每个题目对象包含问题、选项、正确答案等属性:
questions: [
{
id: 1,
text: "Vue的核心特性是什么?",
options: ["组件化", "双向绑定", "虚拟DOM", "全部"],
answer: 3 // 选项索引
},
// 更多题目...
]
答题组件实现
创建答题组件展示题目和选项:

<template>
<div v-for="(question, index) in questions" :key="question.id">
<h3>{{ index + 1 }}. {{ question.text }}</h3>
<ul>
<li v-for="(option, i) in question.options" :key="i">
<input
type="radio"
:id="`q${question.id}-o${i}`"
:name="`q${question.id}`"
:value="i"
v-model="userAnswers[question.id]"
>
<label :for="`q${question.id}-o${i}`">{{ option }}</label>
</li>
</ul>
</div>
<button @click="submitAnswers">提交答案</button>
</template>
状态管理
使用响应式数据存储用户答案:
data() {
return {
userAnswers: {},
questions: [...] // 题目数据
}
},
methods: {
submitAnswers() {
const score = this.questions.reduce((total, question) => {
return total + (this.userAnswers[question.id] === question.answer ? 1 : 0)
}, 0)
alert(`得分: ${score}/${this.questions.length}`)
}
}
进阶功能实现
计时功能:

data() {
return {
timeLeft: 60,
timer: null
}
},
mounted() {
this.timer = setInterval(() => {
if (this.timeLeft <= 0) {
clearInterval(this.timer)
this.submitAnswers()
} else {
this.timeLeft--
}
}, 1000)
},
beforeUnmount() {
clearInterval(this.timer)
}
题目分页:
<template>
<div v-if="currentQuestion">
<h3>{{ currentIndex + 1 }}. {{ currentQuestion.text }}</h3>
<!-- 选项渲染 -->
<button @click="prevQuestion" :disabled="currentIndex === 0">上一题</button>
<button @click="nextQuestion" :disabled="currentIndex === questions.length - 1">下一题</button>
</div>
</template>
<script>
computed: {
currentQuestion() {
return this.questions[this.currentIndex]
}
},
data() {
return {
currentIndex: 0
}
}
</script>
样式优化
添加基础样式提升用户体验:
ul {
list-style: none;
padding: 0;
}
li {
margin: 8px 0;
padding: 8px;
border: 1px solid #eee;
border-radius: 4px;
}
li:hover {
background-color: #f5f5f5;
}
input[type="radio"] {
margin-right: 8px;
}
这个实现方案涵盖了答题系统的基础功能,可以根据具体需求进行扩展,如添加题目分类、难度分级、答题历史记录等功能。






