vue实现问卷题目
Vue 实现问卷题目
在 Vue 中实现问卷题目可以通过组件化和响应式数据管理来完成。以下是实现问卷题目的关键步骤和代码示例。
数据结构设计
问卷数据通常包含题目列表、题目类型(单选、多选、填空等)和用户答案。可以使用如下数据结构:
data() {
return {
questions: [
{
id: 1,
type: 'radio',
title: '您的性别是?',
options: ['男', '女', '其他'],
answer: ''
},
{
id: 2,
type: 'checkbox',
title: '您喜欢哪些编程语言?',
options: ['JavaScript', 'Python', 'Java', 'C++'],
answer: []
},
{
id: 3,
type: 'text',
title: '请简要描述您的项目经验',
answer: ''
}
]
}
}
动态渲染题目
根据题目类型动态渲染不同的输入组件:
<template>
<div v-for="question in questions" :key="question.id">
<h3>{{ question.title }}</h3>
<div v-if="question.type === 'radio'">
<label v-for="option in question.options" :key="option">
<input
type="radio"
:name="'q' + question.id"
:value="option"
v-model="question.answer"
>
{{ option }}
</label>
</div>
<div v-else-if="question.type === 'checkbox'">
<label v-for="option in question.options" :key="option">
<input
type="checkbox"
:value="option"
v-model="question.answer"
>
{{ option }}
</label>
</div>
<div v-else-if="question.type === 'text'">
<textarea v-model="question.answer"></textarea>
</div>
</div>
</template>
表单提交
添加提交按钮和处理函数:
methods: {
submitSurvey() {
console.log('用户答案:', this.questions);
// 这里可以添加提交到后端的逻辑
}
}
验证逻辑
对于必填题目,可以添加验证:
computed: {
isFormValid() {
return this.questions.every(q => {
if (q.required) {
return q.type === 'checkbox' ? q.answer.length > 0 : q.answer !== '';
}
return true;
});
}
}
样式优化
使用 CSS 或 UI 框架(如 Element UI、Vuetify)美化问卷界面:
.question {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #eee;
border-radius: 5px;
}
组件化
将题目组件拆分为单独的可复用组件:

// QuestionComponent.vue
<template>
<div class="question">
<h3>{{ question.title }}</h3>
<component
:is="question.type"
:question="question"
@update="handleUpdate"
/>
</div>
</template>
<script>
import RadioQuestion from './RadioQuestion.vue';
import CheckboxQuestion from './CheckboxQuestion.vue';
import TextQuestion from './TextQuestion.vue';
export default {
components: {
radio: RadioQuestion,
checkbox: CheckboxQuestion,
text: TextQuestion
},
props: ['question'],
methods: {
handleUpdate(value) {
this.$emit('update', value);
}
}
}
</script>
通过以上方法,可以构建一个灵活、可扩展的问卷系统。根据需求可以进一步添加题目跳转逻辑、计时功能、保存进度等高级特性。






