当前位置:首页 > 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 单选实现方法 在 Vue 中实现单选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定单选按钮 通过 v-model 绑定到同一个变量,实现单选效果: <t…

vue实现li多选

vue实现li多选

Vue 实现列表多选功能 在 Vue 中实现列表(<li>)的多选功能可以通过多种方式完成。以下是几种常见的实现方法: 使用 v-model 绑定数组 通过 v-model 绑定一个数组…

vue怎么实现多选

vue怎么实现多选

使用 v-model 绑定数组实现多选 在 Vue 中,可以通过 v-model 绑定一个数组来实现多选功能。当用户选择多个选项时,选中的值会自动添加到数组中。 <template>…

vue实现多选搜索

vue实现多选搜索

Vue 多选搜索实现方法 使用 Element UI 的 Select 组件 Element UI 提供了带有搜索功能的多选组件,适合快速实现需求。 安装 Element UI: npm inst…

vue实现多选日历

vue实现多选日历

Vue 实现多选日历 使用 Vue 实现多选日历功能可以借助现有的日历库或手动构建。以下是两种常见方法: 使用第三方库(如 V-Calendar) 安装 V-Calendar 库: npm ins…

vue 点击实现单选

vue 点击实现单选

实现 Vue 单选点击功能 在 Vue 中实现单选功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-model 绑定 通过 v-model 绑定一个变量,配合 v-for 渲染选…