当前位置:首页 > 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. 添加题目进度显示

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

vue实现答题组件

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

相关文章

vue怎么实现组件缓存

vue怎么实现组件缓存

Vue 实现组件缓存的方法 Vue 提供了内置组件 <keep-alive> 来实现组件缓存,避免重复渲染和销毁组件,提升性能。 基本用法 使用 <keep-alive>…

vue实现组件循环图片

vue实现组件循环图片

Vue 中实现组件循环图片的方法 在 Vue 中,可以通过 v-for 指令循环渲染图片组件。假设有一组图片数据需要循环展示,可以采用以下方式: 数据准备 在组件的 data 或 props 中定义…

vue computed 实现

vue computed 实现

computed 的基本用法 在 Vue 中,computed 用于声明计算属性,这些属性基于响应式依赖进行缓存。只有当依赖发生变化时,计算属性才会重新计算。 new Vue({ data:…

vue 实现过滤

vue 实现过滤

Vue 实现过滤的方法 在 Vue 中实现过滤功能可以通过多种方式完成,包括使用计算属性、自定义过滤器、第三方库等。以下是几种常见的实现方法: 使用计算属性进行过滤 计算属性是 Vue 中最常用的过…

vue compile 实现

vue compile 实现

Vue 编译实现原理 Vue 的编译过程将模板字符串转换为渲染函数,主要分为解析、优化和代码生成三个阶段。 解析阶段(Parse) 将模板字符串转换为抽象语法树(AST)。Vue 使用正则表达式和…

vue实现翻译

vue实现翻译

Vue 实现翻译功能的方法 使用 i18n 插件实现多语言切换 安装 vue-i18n 插件: npm install vue-i18n 创建语言资源文件(如 en.json 和 zh.json)…