Vue实现答题卡
Vue实现答题卡的基本思路
使用Vue实现答题卡需要结合组件化开发、数据绑定和事件处理等特性。答题卡通常包含题目列表、选项选择和提交功能。
创建答题卡组件结构
定义一个Vue组件,包含题目列表和选项。使用v-for渲染题目,v-model绑定用户选择。
<template>
<div class="answer-sheet">
<div v-for="(question, index) in questions" :key="index" class="question">
<h3>{{ question.text }}</h3>
<div v-for="(option, optIndex) in question.options" :key="optIndex" class="option">
<input
type="radio"
:id="`q${index}-opt${optIndex}`"
:name="`question-${index}`"
:value="option.value"
v-model="answers[index]"
>
<label :for="`q${index}-opt${optIndex}`">{{ option.text }}</label>
</div>
</div>
<button @click="submitAnswers">提交答案</button>
</div>
</template>
定义数据模型
在组件中定义题目数据和用户答案存储。

<script>
export default {
data() {
return {
questions: [
{
text: "问题1",
options: [
{ text: "选项A", value: "A" },
{ text: "选项B", value: "B" },
{ text: "选项C", value: "C" }
]
},
// 更多题目...
],
answers: []
}
},
methods: {
submitAnswers() {
console.log("用户答案:", this.answers)
// 这里可以添加提交逻辑
}
}
}
</script>
添加样式美化
为答题卡添加基础样式,提高用户体验。
<style scoped>
.answer-sheet {
max-width: 800px;
margin: 0 auto;
}
.question {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #eee;
border-radius: 5px;
}
.option {
margin: 10px 0;
}
button {
margin-top: 20px;
padding: 10px 20px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
实现答题卡高级功能
可以扩展答题卡功能,如计时器、题目导航和答案校验。

// 添加计时功能
data() {
return {
timeLeft: 60 * 30, // 30分钟
timer: null
}
},
mounted() {
this.timer = setInterval(() => {
if (this.timeLeft > 0) {
this.timeLeft--
} else {
clearInterval(this.timer)
this.submitAnswers()
}
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
题目导航实现
添加题目跳转功能,方便用户快速定位。
<div class="question-nav">
<button
v-for="(_, index) in questions"
:key="index"
@click="scrollToQuestion(index)"
:class="{ active: currentQuestion === index }"
>
{{ index + 1 }}
</button>
</div>
methods: {
scrollToQuestion(index) {
this.currentQuestion = index
const element = document.querySelectorAll('.question')[index]
element.scrollIntoView({ behavior: 'smooth' })
}
}
答案校验与反馈
提交时验证答案并提供反馈。
methods: {
submitAnswers() {
const unanswered = this.answers.filter(a => !a).length
if (unanswered > 0) {
alert(`您还有${unanswered}题未完成`)
return
}
// 计算得分
const score = this.questions.reduce((total, q, i) => {
return total + (this.answers[i] === q.correctAnswer ? q.score : 0)
}, 0)
alert(`您的得分是: ${score}`)
}
}
以上实现提供了答题卡的基础功能和扩展可能性,可根据实际需求进一步调整和完善。






