vue实现试题录入
Vue 实现试题录入功能
数据模型设计
试题数据通常包含题目、选项、答案、类型等字段。可以设计如下数据结构:
question: {
id: '', // 试题ID
title: '', // 题目内容
type: 'single', // 题型:single/multiple/truefalse
options: [ // 选项数组
{ id: 1, text: '' },
{ id: 2, text: '' }
],
answer: [], // 正确答案ID数组
difficulty: 1, // 难度系数
tags: [] // 标签分类
}
表单组件构建
使用Vue的v-model实现双向数据绑定:
<template>
<div class="question-editor">
<input v-model="question.title" placeholder="请输入题目内容">
<select v-model="question.type">
<option value="single">单选题</option>
<option value="multiple">多选题</option>
<option value="truefalse">判断题</option>
</select>
<div v-for="(opt, index) in question.options" :key="opt.id">
<input v-model="opt.text" :placeholder="'选项' + (index+1)">
<button @click="removeOption(index)">删除</button>
</div>
<button @click="addOption">添加选项</button>
</div>
</template>
动态选项管理
实现选项的增删逻辑:
methods: {
addOption() {
const newId = this.question.options.length + 1
this.question.options.push({
id: newId,
text: ''
})
},
removeOption(index) {
this.question.options.splice(index, 1)
}
}
答案选择逻辑
根据题型显示不同的答案选择方式:
<div v-if="question.type === 'single'">
<label v-for="opt in question.options" :key="opt.id">
<input type="radio"
v-model="question.answer"
:value="[opt.id]">
{{ opt.text }}
</label>
</div>
<div v-else-if="question.type === 'multiple'">
<label v-for="opt in question.options" :key="opt.id">
<input type="checkbox"
v-model="question.answer"
:value="opt.id">
{{ opt.text }}
</label>
</div>
数据提交处理
添加提交方法将试题数据保存到后端:
methods: {
async submitQuestion() {
try {
const res = await axios.post('/api/questions', this.question)
console.log('试题保存成功', res.data)
this.resetForm()
} catch (error) {
console.error('保存失败', error)
}
},
resetForm() {
this.question = {
title: '',
type: 'single',
options: [{id:1, text:''}, {id:2, text:''}],
answer: [],
difficulty: 1,
tags: []
}
}
}
富文本编辑器集成
如需复杂题目内容,可集成富文本编辑器:
<template>
<quill-editor v-model="question.title" :options="editorOptions"/>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
export default {
components: { quillEditor },
data() {
return {
editorOptions: {
modules: {
toolbar: [
['bold', 'italic'],
['code-block']
]
}
}
}
}
}
</script>
表单验证
使用Vuelidate进行数据校验:
import { required, minLength } from 'vuelidate/lib/validators'
export default {
validations: {
question: {
title: { required },
options: {
$each: {
text: { required }
}
},
answer: {
required,
minLength: minLength(1)
}
}
}
}
组件化设计
将试题录入拆分为多个组件:

QuestionForm.vue - 主表单容器
QuestionTypeSelect.vue - 题型选择
OptionList.vue - 选项管理
AnswerArea.vue - 答案选择
TagInput.vue - 标签输入
以上实现方案可根据实际需求进行调整,如添加图片上传、公式编辑、试题导入导出等功能。






