当前位置:首页 > VUE

vue实现答题切换

2026-02-20 01:06:11VUE

实现答题切换的基本思路

在Vue中实现答题切换功能,通常需要管理当前题目索引、题目数据列表以及用户答案存储。通过绑定数据与视图,利用Vue的响应式特性实现题目切换时的自动更新。

核心代码实现

1. 定义数据结构和状态

vue实现答题切换

data() {
  return {
    questions: [
      { id: 1, text: "问题1", options: ["A", "B", "C"] },
      { id: 2, text: "问题2", options: ["A", "B", "C"] }
    ],
    currentIndex: 0,
    answers: {}
  }
}

2. 题目切换方法

methods: {
  nextQuestion() {
    if (this.currentIndex < this.questions.length - 1) {
      this.currentIndex++
    }
  },
  prevQuestion() {
    if (this.currentIndex > 0) {
      this.currentIndex--
    }
  }
}

3. 模板部分

vue实现答题切换

<div class="quiz-container">
  <div class="question">
    <h3>{{ questions[currentIndex].text }}</h3>
    <div v-for="(option, index) in questions[currentIndex].options" :key="index">
      <input 
        type="radio" 
        :id="'q'+currentIndex+'o'+index"
        :value="option"
        v-model="answers[currentIndex]">
      <label :for="'q'+currentIndex+'o'+index">{{ option }}</label>
    </div>
  </div>

  <button @click="prevQuestion" :disabled="currentIndex === 0">上一题</button>
  <button @click="nextQuestion" :disabled="currentIndex === questions.length - 1">下一题</button>
</div>

进阶功能实现

进度指示器

<div class="progress">
  <span v-for="(q, index) in questions" 
        :key="q.id"
        :class="{ active: index === currentIndex, answered: answers[index] }"
        @click="currentIndex = index">
    {{ index + 1 }}
  </span>
</div>

答题结果提交

methods: {
  submitAnswers() {
    const unanswered = this.questions.filter((q, index) => !this.answers[index])
    if (unanswered.length > 0) {
      alert(`还有${unanswered.length}题未完成`)
    } else {
      // 提交逻辑
      console.log(this.answers)
    }
  }
}

样式优化建议

.quiz-container {
  max-width: 600px;
  margin: 0 auto;
}
.question {
  margin-bottom: 20px;
}
.progress span {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  margin-right: 5px;
  border-radius: 50%;
  cursor: pointer;
}
.progress span.active {
  background-color: #42b983;
  color: white;
}
.progress span.answered {
  background-color: #f0f0f0;
}

注意事项

  • 使用Vue的响应式特性确保视图与数据同步
  • 考虑添加过渡动画提升用户体验
  • 对于大量题目可考虑分页或虚拟滚动优化性能
  • 答题状态应持久化,避免页面刷新丢失进度

标签: vue
分享给朋友:

相关文章

vue双向实现

vue双向实现

Vue 双向数据绑定的实现原理 Vue 的双向数据绑定主要通过 v-model 指令实现,其核心是结合了数据劫持(Object.defineProperty 或 Proxy)和发布-订阅模式。 数据…

vue查看更多怎么实现

vue查看更多怎么实现

实现 Vue 的“查看更多”功能 数据截取与显示控制 通过 v-if 或 v-show 控制内容的显示与隐藏。初始状态下只显示部分内容,点击“查看更多”后展开完整内容。 <template&…

vue实现活动倒计时

vue实现活动倒计时

实现活动倒计时的基本思路 在Vue中实现活动倒计时通常需要获取当前时间与活动结束时间的差值,并将其转换为天、小时、分钟、秒的格式展示。通过定时器每秒更新显示的时间。 定义倒计时数据 在Vue组件的d…

vue实现生成二维码

vue实现生成二维码

使用qrcode.vue库生成二维码 安装qrcode.vue库: npm install qrcode.vue --save 在Vue组件中使用: <template> &l…

vue SSG实现

vue SSG实现

Vue SSG 实现方法 Vue 的静态站点生成(SSG)可以通过多种工具和框架实现,以下是几种常见的方法: 使用 VuePress VuePress 是一个基于 Vue 的静态站点生成器,适合文…

vue实现画图

vue实现画图

Vue 实现画图功能 在 Vue 中实现画图功能通常需要结合 HTML5 的 <canvas> 元素或第三方库。以下是几种常见的方法: 使用原生 Canvas API 通过 Vue 直…