当前位置:首页 > 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 实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template>…

vue实现快手

vue实现快手

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

vue实现pc

vue实现pc

Vue 实现 PC 端应用开发 Vue.js 是一个流行的前端框架,适用于构建 PC 端 Web 应用。以下是关键步骤和最佳实践: 项目初始化 使用 Vue CLI 或 Vite 创建项目:…

vue实现系统

vue实现系统

Vue 实现系统的核心方法 使用 Vue.js 构建系统时,需结合其响应式特性与组件化开发模式。以下为关键实现路径: 项目初始化与工程配置 通过 Vue CLI 或 Vite 创建项目骨架,推荐选择…

vue实现eventbus

vue实现eventbus

Vue 中实现 EventBus 在 Vue 中,EventBus 是一种跨组件通信的机制,尤其适用于非父子组件之间的数据传递。以下是实现 EventBus 的几种方法: 方法一:使用 Vue 实例…

vue实现dialog

vue实现dialog

Vue 实现 Dialog 的方法 使用 Vue 原生组件实现 Vue 可以通过组件化的方式实现 Dialog,以下是一个简单的实现示例: <template> <div>…