当前位置:首页 > 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 组件实现基础 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。组件的实现包括定义、注册、数据传递和生命周期管理等。 定义组件 组件可以通过单文件组件(.…

vue实现旋转

vue实现旋转

Vue 实现旋转效果的方法 在 Vue 中实现旋转效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 动画 通过 Vue 的 :class 或 :style 绑定 CSS 动画实现旋转效…

vue实现跑车

vue实现跑车

Vue 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

vue 实现grid

vue 实现grid

在Vue中实现Grid布局可以通过多种方式完成,以下是几种常见的方法: 使用CSS Grid布局 CSS Grid是一种强大的布局系统,可以直接在Vue组件的样式中使用。以下是一个简单的示例:…

vue 路由 实现

vue 路由 实现

Vue 路由实现方法 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是实现 Vue 路由的详细步骤: 安装 Vue Router 通过 npm 或 ya…

vue实现必填

vue实现必填

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