vue实现各种问卷
Vue 实现问卷系统的方法
基础问卷表单结构
使用 Vue 的 v-model 绑定表单数据,结合 v-for 动态渲染问题列表。示例代码:
<template>
<div v-for="(question, index) in questions" :key="index">
<label>{{ question.text }}</label>
<input
v-if="question.type === 'text'"
v-model="answers[index]"
type="text"
>
<select v-else-if="question.type === 'select'" v-model="answers[index]">
<option v-for="opt in question.options" :value="opt">{{ opt }}</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
{ text: "姓名", type: "text" },
{ text: "满意度", type: "select", options: ["满意", "一般", "不满意"] }
],
answers: []
}
}
}
</script>
动态添加问题
通过数组方法实现问题管理:
methods: {
addQuestion() {
this.questions.push({
text: "",
type: "text",
options: []
});
},
removeQuestion(index) {
this.questions.splice(index, 1);
}
}
表单验证
使用 Vue 的 computed 属性或第三方库如 VeeValidate:
computed: {
isFormValid() {
return this.answers.every(answer => answer !== "");
}
}
保存问卷数据
通过 API 调用或本地存储:
methods: {
submitForm() {
axios.post('/api/survey', { answers: this.answers })
.then(response => {
alert('提交成功');
});
}
}
可视化结果展示
结合图表库如 ECharts 展示统计结果:
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
const chart = echarts.init(this.$refs.chart);
chart.setOption({
xAxis: { data: ['满意', '一般', '不满意'] },
yAxis: {},
series: [{ data: [30, 20, 10], type: 'bar' }]
});
}
}
</script>
进阶功能实现
-
条件逻辑跳转:通过
watch监听答案变化watch: { answers: { handler(newVal) { if (newVal[0] === '不满意') { this.showFollowUp = true; } }, deep: true } } -
多页问卷:使用动态组件或路由分页
<component :is="currentPageComponent" /> -
拖拽排序:集成
vuedraggable库<draggable v-model="questions"> <div v-for="(item, index) in questions" :key="index"> {{ item.text }} </div> </draggable>
注意事项
- 复杂问卷建议使用专业表单库如
vue-form-generator - 移动端适配需考虑触摸事件和响应式布局
- 数据持久化建议结合本地存储或数据库
- 性能优化可使用虚拟滚动处理长列表







