当前位置:首页 > VUE

vue实现单选多选答题

2026-02-23 14:49:49VUE

Vue 实现单选/多选答题功能

数据准备

定义题目和选项数据,通常在 datasetup 中声明。单选和多选的数据结构类似,但多选需要数组存储答案。

data() {
  return {
    questions: [
      {
        id: 1,
        text: "单选题示例",
        type: "single",
        options: [
          { id: 1, text: "选项A" },
          { id: 2, text: "选项B" }
        ],
        answer: null // 存储选中选项ID
      },
      {
        id: 2,
        text: "多选题示例",
        type: "multiple",
        options: [
          { id: 1, text: "选项A" },
          { id: 2, text: "选项B" }
        ],
        answer: [] // 存储选中选项ID数组
      }
    ]
  }
}

模板渲染

使用 v-for 循环渲染题目和选项,通过 v-model 绑定选中状态。

vue实现单选多选答题

<div v-for="question in questions" :key="question.id">
  <h3>{{ question.text }}</h3>
  <div v-if="question.type === 'single'">
    <label v-for="option in question.options" :key="option.id">
      <input 
        type="radio" 
        :name="'question-' + question.id" 
        :value="option.id" 
        v-model="question.answer"
      >
      {{ option.text }}
    </label>
  </div>
  <div v-else>
    <label v-for="option in question.options" :key="option.id">
      <input 
        type="checkbox" 
        :value="option.id" 
        v-model="question.answer"
      >
      {{ option.text }}
    </label>
  </div>
</div>

答案提交

通过方法处理提交逻辑,验证答案格式(单选为单个值,多选为数组)。

methods: {
  submitAnswers() {
    const answers = this.questions.map(q => ({
      questionId: q.id,
      answer: q.answer
    }));
    console.log("提交的答案:", answers);
    // 实际场景可调用API提交
  }
}

样式优化

添加CSS增强交互体验,例如选中高亮效果。

vue实现单选多选答题

label {
  display: block;
  padding: 8px;
  margin: 4px 0;
  cursor: pointer;
}
label:hover {
  background-color: #f0f0f0;
}
input[type="radio"], 
input[type="checkbox"] {
  margin-right: 8px;
}

动态组件扩展

通过 component :is 实现题型切换,提升代码复用性。

<component 
  :is="question.type === 'single' ? 'RadioQuestion' : 'CheckboxQuestion'" 
  :question="question"
></component>

响应式验证

使用计算属性或 watch 监听答案变化,实时验证完整性。

computed: {
  isAllAnswered() {
    return this.questions.every(q => 
      q.type === 'single' 
        ? q.answer !== null 
        : q.answer.length > 0
    );
  }
}

通过以上步骤可实现完整的答题功能,支持单选和多选题型,具备数据绑定、提交验证和样式交互。实际开发中可根据需求扩展计时、题目切换等功能。

标签: 多选单选
分享给朋友:

相关文章

vue 实现多选框

vue 实现多选框

Vue 实现多选框的方法 使用 v-model 绑定数组 在 Vue 中,可以通过 v-model 绑定一个数组来实现多选框的选择功能。每个复选框的 value 属性会被添加到数组中,取消勾选时则从数…

vue单选按钮实现

vue单选按钮实现

Vue 单选按钮实现方法 在 Vue 中实现单选按钮可以通过 v-model 指令绑定数据,结合 <input type="radio"> 或第三方组件库完成。以下是几种常见实现方式:…

vue实现单选按钮

vue实现单选按钮

实现单选按钮的基本方法 在Vue中实现单选按钮通常使用v-model指令绑定数据,结合input元素的type="radio"属性。以下是一个基础示例: <template> <…

vue实现图片单选

vue实现图片单选

Vue 实现图片单选功能 在 Vue 中实现图片单选功能可以通过多种方式完成,以下是两种常见的实现方法: 方法一:使用 v-model 和单选按钮 通过将单选按钮与图片绑定,利用 v-mod…

elementui多选

elementui多选

ElementUI 多选组件使用指南 ElementUI 提供了 el-select 组件支持多选功能,通过设置 multiple 属性即可启用。以下是具体实现方法和常见场景示例: 基础多选实现 设…

Vue实现级联多选

Vue实现级联多选

Vue 实现级联多选的方法 使用 Element UI 的 Cascader 组件 Element UI 提供了 el-cascader 组件,支持多选功能。通过设置 props 的 multiple…