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

vue实现导入

vue实现导入

Vue 实现文件导入功能 使用 <input type="file"> 元素 在 Vue 模板中添加一个文件输入元素,绑定 change 事件处理函数。 <template>…

vue实现 页面

vue实现 页面

Vue 实现页面的核心方法 创建 Vue 项目 使用 Vue CLI 或 Vite 快速初始化项目。Vue CLI 是官方脚手架工具,适合传统项目;Vite 提供更快的现代构建体验。 npm cre…

vue  实现分页

vue 实现分页

实现分页的基本思路 在Vue中实现分页通常需要结合后端API返回的数据和前端的分页组件。分页的核心逻辑包括计算总页数、处理当前页码变化以及触发数据请求。 分页组件示例 使用Element UI的分页…

vue实现等级选择

vue实现等级选择

实现等级选择的方法 在Vue中实现等级选择功能,可以通过多种方式完成,以下是几种常见的实现方法: 使用v-for渲染星级选择 通过v-for指令循环渲染星级图标,结合点击事件实现等级选择: <…

vue排他思想实现

vue排他思想实现

Vue 排他思想实现 排他思想在 Vue 中通常指多个元素中只能有一个被选中或激活的状态。可以通过数据驱动和条件渲染实现。 使用 v-model 和计算属性 定义一个数据属性存储当前选中项的索引或标…