当前位置:首页 > VUE

vue答题功能实现

2026-01-17 16:15:07VUE

Vue 答题功能实现

数据结构设计

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

vue答题功能实现

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

题目展示组件

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

vue答题功能实现

<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 实现选中状态的视觉反馈。

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中实现右下角弹框,通常需要结合CSS定位和Vue的组件化特性。弹框可以通过绝对定位固定在右下角,并通过Vue控制其显示与隐藏。 创建弹框组件 新建一个Vue组件(如…

vue实现边框

vue实现边框

Vue 实现边框的方法 在 Vue 中实现边框效果可以通过多种方式完成,包括内联样式、CSS 类绑定、动态样式以及使用第三方 UI 库。以下是几种常见的实现方法。 内联样式绑定 使用 Vue 的 :…

ssh vue 实现

ssh vue 实现

使用SSH连接Vue项目部署的服务器 在Vue项目开发或部署过程中,可能需要通过SSH连接到远程服务器进行配置或维护。以下是实现SSH连接并部署Vue项目的关键步骤: 生成SSH密钥对 在本地终端运…

vue实现录像

vue实现录像

Vue 实现录像功能 在 Vue 中实现录像功能通常需要借助浏览器的 MediaDevices API 和 MediaRecorder API。以下是实现步骤: 获取用户摄像头和麦克风权限 使用 n…

轮播vue实现

轮播vue实现

使用 Vue 实现轮播功能 基础轮播实现 安装依赖(如使用 Swiper): npm install swiper vue-awesome-swiper 组件代码示例: <template&…

vue实现div单选

vue实现div单选

Vue 实现 div 单选 在 Vue 中实现 div 单选可以通过 v-model 结合 v-for 和事件绑定来完成。以下是具体实现方法: 模板部分 <template> &l…