当前位置:首页 > VUE

vue 实现答题功能

2026-02-18 12:36:05VUE

Vue 实现答题功能的方法

数据结构和状态管理

使用 Vue 的 dataref(Composition API)存储题目列表和用户答案。例如:

vue 实现答题功能

data() {
  return {
    questions: [
      { id: 1, text: "问题1", options: ["A", "B", "C"], correct: 0 },
      { id: 2, text: "问题2", options: ["A", "B"], correct: 1 }
    ],
    userAnswers: {}
  }
}

动态渲染题目

通过 v-for 循环渲染题目和选项,使用 v-model 绑定用户选择:

vue 实现答题功能

<div v-for="q in questions" :key="q.id">
  <h3>{{ q.text }}</h3>
  <div v-for="(opt, index) in q.options" :key="index">
    <input 
      type="radio" 
      :id="`q${q.id}_opt${index}`" 
      :value="index" 
      v-model="userAnswers[q.id]"
    >
    <label :for="`q${q.id}_opt${index}`">{{ opt }}</label>
  </div>
</div>

提交与验证逻辑

计算得分时遍历用户答案并与正确答案对比:

methods: {
  calculateScore() {
    return this.questions.reduce((score, q) => {
      return score + (this.userAnswers[q.id] === q.correct ? 1 : 0)
    }, 0)
  }
}

进度和结果展示

显示当前题号、总题数和最终结果:

<div>进度: {{ Object.keys(userAnswers).length }}/{{ questions.length }}</div>
<button @click="calculateScore">提交答案</button>
<div v-if="score !== null">得分: {{ score }}/{{ questions.length }}</div>

高级功能扩展

  • 题型支持:通过 question.type 字段区分单选、多选、填空等题型
  • 状态持久化:使用 localStorage 保存答题进度
  • 动画效果:通过 Vue 的 <transition> 添加题目切换动画
  • API 集成:使用 axios 动态加载题目数据

完整示例(Composition API)

<script setup>
import { ref } from 'vue'

const questions = ref([
  // 题目数据
])
const userAnswers = ref({})
const score = ref(null)

const submit = () => {
  score.value = questions.value.reduce((total, q) => {
    return total + (userAnswers.value[q.id] === q.correct ? 1 : 0)
  }, 0)
}
</script>

标签: 功能vue
分享给朋友:

相关文章

vue实现活动倒计时

vue实现活动倒计时

实现活动倒计时的基本思路 在Vue中实现活动倒计时通常需要获取当前时间与活动结束时间的差值,并将其转换为天、小时、分钟、秒的格式展示。通过定时器每秒更新显示的时间。 定义倒计时数据 在Vue组件的d…

eventbus vue实现

eventbus vue实现

EventBus 实现原理 EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。 创建 EventBus 在 Vue 项目中创建一个独立…

vue element实现

vue element实现

Vue Element UI 实现 Vue Element UI 是基于 Vue.js 的组件库,提供丰富的 UI 组件,适合快速开发企业级中后台产品。以下是一些关键实现方法和步骤: 安装 Vue…

vue slot实现

vue slot实现

vue slot 的实现方法 在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式: 默认 slot 默认 slot 是最基础的 slo…

vue实现级联

vue实现级联

Vue 实现级联选择器的方法 级联选择器(Cascader)是常见的表单组件,用于处理多层级联动数据选择(如省市区选择)。以下是几种实现方式: 基于 Element UI 的 el-cascade…

vue实现盖章

vue实现盖章

Vue 实现盖章功能 在Vue中实现盖章功能通常涉及前端UI交互,通过Canvas或SVG绘制印章,并允许用户拖拽或点击放置印章。以下是具体实现方法: 使用Canvas绘制印章 通过HTML5的…