当前位置:首页 > 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 绑定选中状态。

<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增强交互体验,例如选中高亮效果。

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实现多选联动

实现多选联动的基本思路 在Vue中实现多选联动功能,通常需要利用v-model绑定数据、监听选项变化以及动态更新关联选项。以下是几种常见的实现方式: 基于v-model和计算属性 通过v-mode…

vue实现div单选

vue实现div单选

实现 div 单选功能 在 Vue 中实现 div 单选功能可以通过多种方式完成。以下是几种常见的实现方法: 使用 v-model 和计算属性 通过 v-model 绑定一个变量,结合计算属性实现单…

vue怎么实现单选

vue怎么实现单选

实现单选功能的方法 在Vue中实现单选功能可以通过多种方式,以下是几种常见的实现方法: 使用原生HTML单选按钮 通过v-model绑定数据,结合原生<input type="radio"&…

vue实现单选弹窗

vue实现单选弹窗

Vue 实现单选弹窗的方法 使用 Element UI 的 Dialog 和 Radio 组件 安装 Element UI 后,可以通过 Dialog 和 Radio 组件快速实现单选弹窗功能。…

vue实现列表多选

vue实现列表多选

Vue 实现列表多选的方法 使用 v-model 绑定数组 通过 v-model 绑定一个数组,可以轻松实现多选功能。当复选框被选中或取消选中时,数组会自动更新。 <template>…

vue实现全选 单选

vue实现全选 单选

Vue实现全选与单选功能 在Vue中实现全选和单选功能通常涉及数据绑定、事件处理和计算属性的使用。以下是两种常见的实现方式: 基于数组的复选框实现 <template> <di…