网页vue实现问卷功能
实现问卷功能的Vue组件设计
使用Vue.js实现问卷功能需要设计动态表单组件、问题类型管理和数据提交逻辑。以下是关键实现步骤:
创建问卷数据结构
data() {
return {
questions: [
{
id: 1,
type: 'radio',
title: '您的性别是?',
options: ['男', '女', '其他'],
required: true
},
{
id: 2,
type: 'checkbox',
title: '您喜欢哪些编程语言?',
options: ['JavaScript', 'Python', 'Java', 'C++'],
required: false
}
],
answers: {}
}
}
动态渲染问题组件
<template v-for="question in questions" :key="question.id">
<div class="question-item">
<h3>{{ question.title }}</h3>
<component
:is="getComponentType(question.type)"
:question="question"
v-model="answers[question.id]"
/>
</div>
</template>
问题类型组件映射
methods: {
getComponentType(type) {
const componentMap = {
'radio': 'RadioQuestion',
'checkbox': 'CheckboxQuestion',
'text': 'TextQuestion'
}
return componentMap[type] || 'TextQuestion'
}
}
不同题型组件实现
单选题组件
<template>
<div v-for="(option, index) in question.options" :key="index">
<input
type="radio"
:id="`q${question.id}_o${index}`"
:name="`q${question.id}`"
:value="option"
v-model="selectedOption"
/>
<label :for="`q${question.id}_o${index}`">{{ option }}</label>
</div>
</template>
<script>
export default {
props: ['question', 'value'],
computed: {
selectedOption: {
get() { return this.value },
set(val) { this.$emit('input', val) }
}
}
}
</script>
多选题组件
<template>
<div v-for="(option, index) in question.options" :key="index">
<input
type="checkbox"
:id="`q${question.id}_o${index}`"
:value="option"
v-model="selectedOptions"
/>
<label :for="`q${question.id}_o${index}`">{{ option }}</label>
</div>
</template>
<script>
export default {
props: ['question', 'value'],
data() {
return {
selectedOptions: this.value || []
}
},
watch: {
selectedOptions(val) {
this.$emit('input', val)
}
}
}
</script>
表单验证与提交
添加验证逻辑
methods: {
validateForm() {
return this.questions.every(question => {
if (question.required) {
const answer = this.answers[question.id]
return answer !== undefined &&
(Array.isArray(answer) ? answer.length > 0 : answer !== '')
}
return true
})
}
}
提交处理
methods: {
submitSurvey() {
if (!this.validateForm()) {
alert('请完成所有必答题')
return
}
axios.post('/api/survey', {
surveyId: this.surveyId,
answers: this.answers
}).then(response => {
this.$router.push('/thank-you')
})
}
}
高级功能扩展
动态添加问题
methods: {
addQuestion(type) {
const newQuestion = {
id: Date.now(),
type: type,
title: '',
options: type === 'text' ? [] : ['选项1', '选项2'],
required: false
}
this.questions.push(newQuestion)
}
}
问题排序功能
import draggable from 'vuedraggable'
export default {
components: { draggable },
methods: {
onSort() {
// 更新问题顺序后可以保存到数据库
}
}
}
实现条件逻辑
watch: {
answers: {
deep: true,
handler(newVal) {
this.questions.forEach(q => {
if (q.conditional) {
q.hidden = !this.checkCondition(q.conditional, newVal)
}
})
}
}
}
以上实现提供了完整的问卷系统基础功能,可根据实际需求扩展更多题型和交互功能。关键点在于动态组件渲染、数据双向绑定和表单验证机制的设计。







