vue实现试卷预览
Vue 实现试卷预览功能
实现试卷预览功能需要结合 Vue 的数据绑定、组件化和动态渲染特性。以下是具体实现方法:
数据结构设计
使用 Vue 的 data 或 props 定义试卷数据结构,通常包含题目列表、题型、选项等信息:
data() {
return {
paper: {
title: '数学试卷',
questions: [
{
id: 1,
type: 'single', // 单选题
content: '1 + 1等于多少?',
options: ['1', '2', '3', '4'],
answer: '2'
},
{
id: 2,
type: 'multi', // 多选题
content: '以下哪些是偶数?',
options: ['1', '2', '4', '5'],
answer: ['2', '4']
}
]
}
}
}
动态组件渲染
根据题型动态渲染不同组件:

<template>
<div class="paper-preview">
<h2>{{ paper.title }}</h2>
<div v-for="(question, index) in paper.questions" :key="question.id">
<div class="question">
<p>{{ index + 1 }}. {{ question.content }}</p>
<!-- 单选题 -->
<div v-if="question.type === 'single'">
<div v-for="(option, i) in question.options" :key="i">
<input type="radio" :name="'q'+question.id" :value="option">
<label>{{ option }}</label>
</div>
</div>
<!-- 多选题 -->
<div v-else-if="question.type === 'multi'">
<div v-for="(option, i) in question.options" :key="i">
<input type="checkbox" :name="'q'+question.id" :value="option">
<label>{{ option }}</label>
</div>
</div>
</div>
</div>
</div>
</template>
样式优化
添加 CSS 美化预览界面:
.paper-preview {
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f9f9f9;
}
.question {
margin-bottom: 20px;
padding: 15px;
background: white;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
答案校验功能
添加提交按钮和校验逻辑:

methods: {
submitAnswers() {
const answers = {}
this.paper.questions.forEach(q => {
if (q.type === 'single') {
answers[q.id] = document.querySelector(`input[name="q${q.id}"]:checked`)?.value
} else {
answers[q.id] = Array.from(document.querySelectorAll(`input[name="q${q.id}"]:checked`))
.map(el => el.value)
}
})
console.log('用户答案:', answers)
// 可添加答案比对逻辑
}
}
响应式布局
使用 Vue 的响应式特性确保数据变化时界面自动更新:
watch: {
'paper.questions': {
deep: true,
handler() {
// 数据变化时可执行的操作
}
}
}
组件化拆分
对于复杂试卷,建议拆分为多个组件:
<template>
<div>
<question-item
v-for="(q, i) in paper.questions"
:key="q.id"
:question="q"
:index="i"
@answer-selected="handleAnswer"
/>
</div>
</template>
通过以上方法可以实现一个功能完整的试卷预览系统,支持多种题型展示、答案选择和基本校验功能。实际开发中可根据需求扩展批改功能、计时功能或保存进度等特性。






