当前位置:首页 > VUE

vue实现答题组件

2026-03-08 12:06:37VUE

Vue 实现答题组件

数据准备

定义一个包含题目、选项和正确答案的数据结构。通常使用数组存储题目列表,每个题目对象包含题目内容、选项数组和正确答案索引。

data() {
  return {
    questions: [
      {
        question: "Vue.js 是什么?",
        options: ["前端框架", "编程语言", "数据库", "操作系统"],
        answer: 0
      },
      // 更多题目...
    ],
    currentIndex: 0,
    selectedOption: null,
    score: 0
  }
}

组件模板

创建答题界面模板,显示当前题目、选项列表和导航按钮。使用 v-for 渲染选项列表,v-model 绑定用户选择。

<template>
  <div class="quiz-container">
    <h3>{{ questions[currentIndex].question }}</h3>
    <ul>
      <li v-for="(option, index) in questions[currentIndex].options" :key="index">
        <input 
          type="radio" 
          :id="'option-' + index" 
          :value="index" 
          v-model="selectedOption"
        >
        <label :for="'option-' + index">{{ option }}</label>
      </li>
    </ul>
    <button @click="submitAnswer">提交</button>
    <button @click="nextQuestion" :disabled="currentIndex >= questions.length - 1">
      下一题
    </button>
  </div>
</template>

逻辑实现

实现答题验证和题目切换逻辑。提交答案时检查是否正确并更新分数,切换题目时重置选择状态。

methods: {
  submitAnswer() {
    if (this.selectedOption === this.questions[this.currentIndex].answer) {
      this.score++
      alert("回答正确!")
    } else {
      alert("回答错误!")
    }
  },
  nextQuestion() {
    if (this.currentIndex < this.questions.length - 1) {
      this.currentIndex++
      this.selectedOption = null
    }
  }
}

样式优化

添加基础样式提升用户体验,包括选项高亮、按钮状态和布局调整。

.quiz-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #eee;
  cursor: pointer;
}

li:hover {
  background-color: #f5f5f5;
}

button {
  margin: 10px 5px;
  padding: 8px 16px;
}

进度显示

添加进度条或文字提示显示当前答题进度,帮助用户了解整体情况。

<div class="progress">
  题目 {{ currentIndex + 1 }} / {{ questions.length }}
</div>

结果统计

在最后一道题完成后显示总分和答题情况总结。

vue实现答题组件

computed: {
  isQuizFinished() {
    return this.currentIndex === this.questions.length - 1
  }
}
<div v-if="isQuizFinished" class="result">
  <h3>测试完成!</h3>
  <p>你的得分: {{ score }} / {{ questions.length }}</p>
</div>

标签: 组件vue
分享给朋友:

相关文章

vue实现条件判断

vue实现条件判断

Vue 条件判断实现方法 Vue 提供了多种方式实现条件判断,可以根据不同场景选择合适的方式。 v-if / v-else-if / v-else 这是 Vue 中最常用的条件渲染指令,根据表达式的…

vue实现节流

vue实现节流

vue实现节流的方法 在Vue中实现节流(throttle)功能,通常用于限制高频事件的触发频率,例如滚动、输入或按钮点击。以下是几种常见的实现方式: 使用Lodash的throttle函数 安装L…

vue实现试卷

vue实现试卷

Vue实现试卷系统的基本思路 使用Vue.js构建试卷系统需要结合组件化开发、状态管理和后端数据交互。核心功能包括题目展示、答题逻辑、计时器和提交答案。 核心功能模块划分 试卷组件结构 试卷容器组…

vue实现树形

vue实现树形

Vue 实现树形组件 在 Vue 中实现树形结构通常需要递归组件和动态数据绑定。以下是实现树形组件的几种常见方法。 递归组件实现 递归组件是 Vue 中实现树形结构的核心方法。通过组件调用自身,可以…

vue原生实现

vue原生实现

Vue 原生实现方法 在 Vue 中实现原生功能通常指直接使用 Vue 的核心特性(如指令、响应式数据、组件等)而非依赖第三方库。以下是几种常见场景的原生实现方式: 数据绑定与响应式更新 Vue 的…

vue实现点击跳转

vue实现点击跳转

Vue 实现点击跳转的方法 在 Vue 中实现点击跳转可以通过以下几种方式: 使用 router-link router-link 是 Vue Router 提供的组件,用于声明式导航。适合在模板中…