当前位置:首页 > VUE

vue答题功能实现

2026-01-17 16:15:07VUE

Vue 答题功能实现

数据结构设计

使用 Vue 的响应式数据管理题目和答案。通常需要一个数组存储题目列表,每个题目包含题干、选项、正确答案等字段。

data() {
  return {
    questions: [
      {
        id: 1,
        title: "Vue 的核心特性是什么?",
        options: ["组件化", "双向数据绑定", "虚拟DOM", "全部"],
        answer: 3 // 正确答案索引
      },
      // 更多题目...
    ],
    currentIndex: 0, // 当前题目索引
    selectedAnswer: null, // 用户选择的答案
    score: 0 // 得分
  }
}

题目展示组件

通过计算属性获取当前题目,使用 v-for 渲染选项列表。

<template>
  <div v-if="currentQuestion">
    <h3>{{ currentQuestion.title }}</h3>
    <ul>
      <li 
        v-for="(option, index) in currentQuestion.options" 
        :key="index"
        @click="selectAnswer(index)"
        :class="{ 'selected': selectedAnswer === index }"
      >
        {{ option }}
      </li>
    </ul>
    <button @click="submitAnswer">提交答案</button>
  </div>
</template>

答案选择逻辑

实现答案选择和提交的逻辑,包括验证答案和计分功能。

methods: {
  selectAnswer(index) {
    this.selectedAnswer = index;
  },
  submitAnswer() {
    if (this.selectedAnswer === null) return;

    const isCorrect = this.selectedAnswer === this.currentQuestion.answer;
    if (isCorrect) this.score++;

    // 进入下一题或结束
    if (this.currentIndex < this.questions.length - 1) {
      this.currentIndex++;
      this.selectedAnswer = null;
    } else {
      alert(`测试结束,得分: ${this.score}/${this.questions.length}`);
    }
  }
},
computed: {
  currentQuestion() {
    return this.questions[this.currentIndex];
  }
}

状态样式反馈

通过动态 class 实现选中状态的视觉反馈。

vue答题功能实现

li.selected {
  background-color: #42b983;
  color: white;
}

进阶功能

  1. 计时功能:使用 setInterval 实现答题倒计时
  2. 题目分类:添加分类标签实现按类别筛选
  3. 结果分析:答题后显示错题解析
  4. 持久化存储:通过 localStorage 保存答题进度
// 计时器示例
data() {
  return {
    timeLeft: 30
  }
},
mounted() {
  this.timer = setInterval(() => {
    if (this.timeLeft > 0) this.timeLeft--;
    else this.submitAnswer();
  }, 1000);
},
beforeDestroy() {
  clearInterval(this.timer);
}

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

相关文章

vue实现弹窗可切换

vue实现弹窗可切换

实现弹窗可切换的 Vue 方案 动态组件切换 通过 Vue 的 <component :is="currentComponent"> 动态加载不同弹窗组件,结合 v-if 控制显示状态。…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

vue实现心电图

vue实现心电图

Vue 实现心电图效果 在 Vue 中实现心电图效果通常需要结合 Canvas 或 SVG 进行动态绘图,模拟心电图数据的实时变化。以下是两种实现方式的核心思路和代码示例: 使用 Canvas 绘制…

vue实现烟花

vue实现烟花

Vue 实现烟花效果 在 Vue 中实现烟花效果可以通过结合 CSS 动画和 JavaScript 动态生成烟花元素。以下是具体实现方法: 动态生成烟花元素 通过 Vue 的 v-for 动态生成烟…

前端vue实现概率

前端vue实现概率

Vue实现概率功能的方法 在Vue中实现概率功能通常涉及随机数生成和概率计算。以下是几种常见实现方式: 基础概率实现 使用Math.random()生成0到1之间的随机数,与设定概率比较:…

使用vue实现搜索

使用vue实现搜索

使用 Vue 实现搜索功能 基础搜索实现 在 Vue 中实现搜索功能通常涉及数据绑定、事件监听和列表过滤。以下是一个简单的实现方式: <template> <div>…