vue实现试题录入
实现试题录入功能
使用Vue实现试题录入功能需要结合表单组件、状态管理和数据提交逻辑。以下是具体实现方案:
基础表单结构
创建包含题目类型、题干、选项、答案等字段的表单:
<template>
<div class="question-form">
<form @submit.prevent="submitQuestion">
<div>
<label>题目类型</label>
<select v-model="question.type">
<option value="single">单选题</option>
<option value="multiple">多选题</option>
<option value="judge">判断题</option>
</select>
</div>
<div>
<label>题干</label>
<textarea v-model="question.content"></textarea>
</div>
<div v-if="showOptions">
<div v-for="(option, index) in question.options" :key="index">
<input type="text" v-model="option.text">
<button @click="removeOption(index)">删除</button>
</div>
<button @click="addOption">添加选项</button>
</div>
<div>
<label>正确答案</label>
<div v-if="question.type === 'single'">
<select v-model="question.answer">
<option v-for="(option, index) in question.options"
:value="option.value">
选项{{ index+1 }}
</option>
</select>
</div>
</div>
<button type="submit">提交</button>
</form>
</div>
</template>
数据模型与逻辑处理
在Vue组件中定义数据模型和操作方法:
<script>
export default {
data() {
return {
question: {
type: 'single',
content: '',
options: [
{ text: '', value: 'A' },
{ text: '', value: 'B' }
],
answer: ''
}
}
},
computed: {
showOptions() {
return this.question.type !== 'judge'
}
},
methods: {
addOption() {
const nextChar = String.fromCharCode(
65 + this.question.options.length
)
this.question.options.push({
text: '',
value: nextChar
})
},
removeOption(index) {
this.question.options.splice(index, 1)
},
submitQuestion() {
// 验证逻辑
if(!this.question.content) {
alert('请输入题干内容')
return
}
// 提交到API
this.$axios.post('/api/questions', this.question)
.then(response => {
alert('提交成功')
this.resetForm()
})
},
resetForm() {
this.question = {
type: 'single',
content: '',
options: [
{ text: '', value: 'A' },
{ text: '', value: 'B' }
],
answer: ''
}
}
}
}
</script>
高级功能实现
对于更复杂的试题录入需求,可以考虑以下增强功能:
富文本编辑器集成 使用第三方编辑器如Quill或TinyMCE:
import { QuillEditor } from '@vueup/vue-quill'
components: { QuillEditor }
图片上传支持
methods: {
handleImageUpload(file) {
const formData = new FormData()
formData.append('image', file)
this.$axios.post('/api/upload', formData)
.then(response => {
this.question.images.push(response.data.url)
})
}
}
题目分类管理
data() {
return {
categories: [],
question: {
categoryId: null
// ...其他字段
}
}
},
mounted() {
this.fetchCategories()
},
methods: {
fetchCategories() {
this.$axios.get('/api/categories')
.then(response => {
this.categories = response.data
})
}
}
表单验证增强
使用Vuelidate等验证库确保数据完整性:
import { required, minLength } from 'vuelidate/lib/validators'
validations: {
question: {
content: { required },
options: {
$each: {
text: { required }
}
},
answer: { required }
}
}
状态持久化
考虑使用Vuex管理试题状态,便于多组件共享:
// store/modules/questions.js
const actions = {
async addQuestion({ commit }, question) {
const response = await api.addQuestion(question)
commit('ADD_QUESTION', response.data)
return response
}
}
实现试题录入功能时,应根据实际需求调整字段和验证规则,确保用户友好性和数据完整性。对于高频使用的系统,建议加入自动保存、版本控制等进阶功能。







