当前位置:首页 > 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
分享给朋友:

相关文章

computed vue 实现

computed vue 实现

computed 在 Vue 中的基本用法 Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。 export defaul…

vue筛选实现

vue筛选实现

Vue 筛选实现方法 使用计算属性实现筛选 计算属性是 Vue 中实现数据筛选的常用方式。通过定义一个计算属性,可以根据输入的条件动态过滤数据。 <template> <div…

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.conf…

vue实现必填

vue实现必填

Vue 实现表单必填验证的方法 在Vue中实现表单必填验证可以通过多种方式完成,以下是几种常见的方法: 使用HTML5原生属性 最简单的必填验证可以通过HTML5的required属性实现: &l…

vue实现注销

vue实现注销

实现用户注销功能 在Vue应用中实现用户注销功能通常涉及清除用户会话、重置应用状态并跳转到登录页面。以下是具体实现方法: 清除用户认证信息 使用Vuex或Pinia管理用户状态时,需在注销时重置存储…

vue实现快手

vue实现快手

Vue 实现类似快手的功能 Vue.js 是一个渐进式 JavaScript 框架,适合构建复杂的单页应用。要实现类似快手的功能,可以结合 Vue 和相关技术栈进行开发。 核心功能模块 视频流展示…