当前位置:首页 > VUE

vue实现问卷题目

2026-01-17 22:23:51VUE

Vue 实现问卷题目

数据模型设计

使用 Vue 的响应式特性管理问卷数据,通常设计为嵌套结构:

data() {
  return {
    questionnaire: {
      title: "用户满意度调查",
      questions: [
        {
          id: 1,
          type: "radio", // 单选/多选/文本等
          title: "您对产品满意度如何?",
          options: ["非常满意", "满意", "一般", "不满意"],
          required: true
        },
        {
          id: 2,
          type: "textarea",
          title: "请提出改进建议:",
          required: false
        }
      ]
    },
    answers: {} // 存储用户回答
  }
}

动态组件渲染

根据题目类型渲染不同输入组件:

<template>
  <div v-for="q in questionnaire.questions" :key="q.id">
    <h3>{{ q.title }}<span v-if="q.required">*</span></h3>

    <!-- 单选 -->
    <div v-if="q.type === 'radio'">
      <label v-for="opt in q.options" :key="opt">
        <input 
          type="radio" 
          v-model="answers[q.id]" 
          :value="opt"
          :required="q.required">
        {{ opt }}
      </label>
    </div>

    <!-- 文本输入 -->
    <textarea 
      v-else-if="q.type === 'textarea'"
      v-model="answers[q.id]"
      :required="q.required">
    </textarea>
  </div>
</template>

表单验证

通过计算属性或方法实现验证:

vue实现问卷题目

computed: {
  isValid() {
    return this.questionnaire.questions.every(q => {
      return !q.required || this.answers[q.id]?.trim()
    })
  }
}

提交处理

异步提交时处理数据:

methods: {
  async submit() {
    if (!this.isValid) return alert("请完成必填项");

    const payload = {
      questionnaireId: this.questionnaire.id,
      answers: this.answers
    };

    try {
      await api.submitSurvey(payload);
      this.$router.push('/thank-you');
    } catch (error) {
      console.error("提交失败:", error);
    }
  }
}

高级功能实现

题目逻辑跳转
通过 watch 监听答案变化:

vue实现问卷题目

watch: {
  answers: {
    handler(newVal) {
      if (newVal[1] === "不满意") {
        this.showFollowUpQuestion = true;
      }
    },
    deep: true
  }
}

拖拽排序
使用 vue-draggable 库:

<draggable 
  v-model="questionnaire.questions" 
  @end="saveQuestionOrder">
  <!-- 题目列表 -->
</draggable>

实时保存
添加防抖自动保存:

import { debounce } from 'lodash';

created() {
  this.debouncedSave = debounce(this.saveDraft, 3000);
},

watch: {
  answers: {
    handler() {
      this.debouncedSave();
    },
    deep: true
  }
}

标签: 问卷题目
分享给朋友:

相关文章

vue实现题目列表

vue实现题目列表

Vue实现题目列表的方法 数据准备 在Vue中实现题目列表需要先准备题目数据。通常将题目数据存储在组件的data或通过API从后端获取。示例数据结构如下: data() { return {…

vue实现题目翻页

vue实现题目翻页

Vue实现题目翻页功能 使用v-for和计算属性实现分页 在Vue中可以通过计算属性对题目列表进行分页处理,结合v-for渲染当前页的题目。定义currentPage和pageSize控制分页逻辑…

css制作题目

css制作题目

使用CSS制作题目样式 通过CSS可以自定义题目的样式,包括字体、颜色、间距等,使其更符合设计需求。 HTML结构示例 <div class="question"> <h3…

php实现问卷制作

php实现问卷制作

PHP实现问卷制作的基本步骤 使用PHP创建问卷系统需要结合数据库(如MySQL)存储问题和用户回答,前端HTML/CSS用于展示表单,后端PHP处理逻辑。以下是关键实现方法: 数据库设计…

vue实现各种问卷

vue实现各种问卷

Vue 实现问卷系统的方法 基础问卷表单结构 使用 Vue 的 v-model 绑定表单数据,结合 v-for 动态渲染问题列表。示例代码: <template> <div v…

vue实现题目翻页

vue实现题目翻页

实现思路 在Vue中实现题目翻页功能,通常需要结合分页逻辑和组件状态管理。核心是通过当前页码控制题目数据的显示,并提供翻页按钮切换页码。 基础实现方案 数据准备 准备题目数组,每个元素代表…