当前位置:首页 > VUE

vue实现答题组件

2026-02-17 00:06:13VUE

Vue 实现答题组件

数据结构设计

使用数组存储题目数据,每个题目对象包含问题、选项、正确答案等字段:

data() {
  return {
    questions: [
      {
        id: 1,
        text: "Vue的核心特性是什么?",
        options: ["组件化", "双向数据绑定", "虚拟DOM", "全部"],
        answer: 3
      }
    ],
    currentIndex: 0,
    selectedOption: null
  }
}

模板渲染

通过v-for渲染题目和选项,使用v-model绑定用户选择:

<template>
  <div class="quiz-container">
    <h3>{{ questions[currentIndex].text }}</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>
  </div>
</template>

交互逻辑

实现答案验证和题目切换功能:

methods: {
  submitAnswer() {
    const isCorrect = this.selectedOption === this.questions[this.currentIndex].answer
    alert(isCorrect ? '回答正确' : '回答错误')

    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;
}
button {
  margin-top: 20px;
  padding: 8px 16px;
}

进阶功能实现

  1. 添加计时器组件

    data() {
    return {
     timeLeft: 30,
     timer: null
    }
    },
    mounted() {
    this.timer = setInterval(() => {
     if(this.timeLeft > 0) {
       this.timeLeft--
     } else {
       clearInterval(this.timer)
       alert('时间到!')
     }
    }, 1000)
    }
  2. 实现分数统计

    data() {
    return {
     score: 0
    }
    },
    methods: {
    submitAnswer() {
     if(this.selectedOption === this.questions[this.currentIndex].answer) {
       this.score += 10
     }
     // 其他逻辑...
    }
    }
  3. 添加题目进度显示

    vue实现答题组件

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

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

相关文章

vue登录逻辑的实现

vue登录逻辑的实现

Vue 登录逻辑实现 前端实现 创建登录组件 在 Vue 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含表单元素,如用户名和密码输入框,以及提交按钮。 <template&…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model="…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,支…

lua 实现vue

lua 实现vue

在 Lua 中实现类似 Vue 的响应式框架需要模拟 Vue 的核心功能,包括数据绑定、模板渲染和依赖追踪。以下是实现的关键思路和代码示例: 响应式数据绑定 使用 Lua 的 __index 和 _…

vue 实现协同

vue 实现协同

Vue 实现协同编辑的方案 协同编辑指多个用户同时编辑同一文档并实时同步更改。Vue 结合相关库和技术可轻松实现该功能。 使用 WebSocket 实现实时通信 WebSocket 提供全双工通信,…

vue实现录音

vue实现录音

Vue 实现录音功能 在 Vue 中实现录音功能可以通过浏览器提供的 MediaRecorder API 完成。以下是具体实现方法: 引入依赖 确保项目支持现代浏览器 API,无需额外安装库。若需兼…