
简介这是一套轻量级、纯前端实现的H5刷题应用源码面向前端初学者、教学演示者及快速搭建学习工具的开发者解决无服务器环境下的在线练习场景需求。项目采用VueAxiosIView技术栈完全不依赖后端与数据库所有题目数据以JSON格式含2016–2018年共3个年份题库内嵌于前端支持随机刷题、章节练习、模拟考试、错题重做四种核心模式兼顾实用性与教学可拆解性。压缩包共23个文件含4个JSVue/axios/iview核心逻辑、3个HTML主页面、题库页、类型页、3个JSON结构化题库、4个TXT含必看安装说明、README、zgdx资源说明及Python转换脚本指引、1个PNGlogo、1个DOCX题库模板及1个PY脚本timuToJson.py用于txt题库转JSON整体仅544KB即下即用。目前已有144人学习下载读者可直接部署运行、深入理解前端本地数据管理方案并复用其模块化目录结构与四种模式交互逻辑快速二次开发定制化刷题工具。1. 一个不碰后端、不连数据库的刷题H5网站凭什么能跑通四种模式你打开一个刷题页面点击「顺序刷题」题目逐道加载切换「随机刷题」每刷新一次题序都不同选「错题重练」它真能记住你上次点错的题再点「模拟考试」倒计时开始、提交后立刻出分——而整个过程没发过一条请求到服务器没读写过一行数据库记录。这不是演示demo而是真实可部署的H5应用所有逻辑在浏览器里闭环题库静态打包进前端资源状态靠 localStorage 内存缓存双层管理。它适合技术面试官快速搭内部题库、教育机构做轻量级课前测、甚至学生自己整理错题集。核心不在“多炫”而在“零运维依赖”你只要有一台能放静态文件的服务器甚至 GitHub Pages、Vercel、阿里云OSS解压 zip、扔上去、开个链接刷题就上线。标题里的“无后端无数据库”不是偷懒是把题型结构、答题状态、统计逻辑全部用 Vue 响应式 Axios 模拟请求 JSON 题库文件落地为可复现、可调试、可二次封装的纯前端工程。2. 四种刷题模式如何用 Vue 静态题库实现闭环逻辑2.1 题库结构设计JSON 文件承载全部题目与元数据刷题应用的核心不是界面而是题库的组织方式。本项目采用扁平化 JSON 结构每个题目为独立对象统一存于src/assets/data/questions.json中[ { id: q001, type: single-choice, stem: Vue 实例中 data 选项必须是, options: [函数, 对象, 数组, 字符串], answer: 0, analysis: data 必须是函数避免组件复用时共享同一引用。, tags: [vue, 基础], difficulty: 1 }, { id: q002, type: true-false, stem: axios 默认发送 GET 请求时会自动序列化 URL 参数。, answer: true, analysis: 是的axios.get(url, { params: { a: 1 } }) 会拼成 ?a1, tags: [axios, http], difficulty: 2 } ]提示type字段决定渲染组件单选/多选/判断/代码填空difficulty用于「模拟考试」按难度抽题tags支持按标签筛选题库。这种结构不依赖数据库 schema修改题目只需编辑 JSON无需改后端接口或迁移脚本。2.2 Vue 组件分层按模式拆解业务逻辑复用底层题库服务项目采用组合式 APIVue 3将题库操作抽象为useQuestionBank()composable// src/composables/useQuestionBank.js import questions from /assets/data/questions.json export function useQuestionBank() { const allQuestions ref(questions) const currentMode ref(sequential) // sequential | random | mistakes | exam const mistakeIds ref(JSON.parse(localStorage.getItem(mistakeIds) || [])) // 顺序刷题按 id 排序取 nextIndex const getSequentialQuestion (index) allQuestions.value[index] // 随机刷题打乱数组并缓存副本避免每次调用都 shuffle const shuffledQuestions computed(() { const arr [...allQuestions.value] for (let i arr.length - 1; i 0; i--) { const j Math.floor(Math.random() * (i 1)) [arr[i], arr[j]] [arr[j], arr[i]] } return arr }) // 错题重练过滤出 localStorage 记录的错题 ID const getMistakeQuestions () allQuestions.value.filter(q mistakeIds.value.includes(q.id)) // 模拟考试按 difficulty 分层抽题例如简单×5 中等×3 困难×2 const getExamQuestions () { const levels [1, 2, 3] const counts [5, 3, 2] return levels.flatMap((level, i) allQuestions.value .filter(q q.difficulty level) .sort(() 0.5 - Math.random()) .slice(0, counts[i]) ) } return { allQuestions, mistakeIds, getSequentialQuestion, shuffledQuestions, getMistakeQuestions, getExamQuestions } }该 composable 封装了四种模式的数据获取逻辑各模式页面如SequentialView.vue只负责调用对应方法不感知题库来源或存储细节。mistakeIds使用 localStorage 持久化避免刷新丢失错题记录——这是“无后端”下最轻量可靠的用户状态保存方案。2.3 Axios 的“伪请求”封装拦截所有 API 调用返回本地 JSON项目中所有axios.get(/api/questions)类请求实际由src/utils/mockAxios.js拦截并返回本地数据// src/utils/mockAxios.js import axios from axios import questions from /assets/data/questions.json // 拦截所有 GET 请求匹配 /api/ 开头路径 axios.interceptors.request.use(config { if (config.method get config.url.startsWith(/api/)) { // 模拟网络延迟 return new Promise(resolve { setTimeout(() { const mockData { /api/questions: questions, /api/user/stats: { total: 128, correct: 94, accuracy: 73.4 } } resolve({ data: mockData[config.url] || [], status: 200, statusText: OK }) }, 300) }) } return config }) export default axios注意此封装不替换 axios 实例而是通过拦截器劫持请求。它让 Vue 组件代码保持与真实 API 一致如await axios.get(/api/questions)便于未来有后端时无缝切换——只需移除该拦截器无需改业务逻辑。这也是企业级 Vue 项目常用策略而非简单用import替代请求。3. 四种模式的具体实现与交互细节3.1 顺序刷题线性推进 进度条 答题卡锚点跳转SequentialView.vue使用v-for渲染题目列表但关键在于分页控制与答题卡联动template div classsequential-container !-- 进度条 -- div classprogress-bar div classprogress-fill :style{ width: ${(currentIndex / totalQuestions) * 100}% } /div /div !-- 当前题目 -- QuestionCard :questioncurrentQuestion submithandleAnswerSubmit / !-- 答题卡小圆点表示题号点击跳转 -- div classanswer-card span v-for(q, idx) in allQuestions :keyq.id clickgoToQuestion(idx) :class{ active: idx currentIndex } classdot /span /div /div /template script setup import { ref, computed } from vue import { useQuestionBank } from /composables/useQuestionBank import QuestionCard from /components/QuestionCard.vue const { allQuestions, getSequentialQuestion } useQuestionBank() const currentIndex ref(0) const totalQuestions computed(() allQuestions.value.length) const currentQuestion computed(() getSequentialQuestion(currentIndex.value)) const goToQuestion (idx) { if (idx 0 idx totalQuestions.value) { currentIndex.value idx } } const handleAnswerSubmit (isCorrect) { // 记录错题到 localStorage if (!isCorrect) { const ids JSON.parse(localStorage.getItem(mistakeIds) || []) if (!ids.includes(currentQuestion.value.id)) { ids.push(currentQuestion.value.id) localStorage.setItem(mistakeIds, JSON.stringify(ids)) } } // 自动进入下一题 if (currentIndex.value totalQuestions.value - 1) { currentIndex.value } } /script关键参数说明currentIndex控制当前题索引goToQuestion()实现任意题号跳转handleAnswerSubmit()在答错时更新mistakeIds为「错题重练」提供数据源。进度条宽度由(currentIndex / totalQuestions) * 100动态计算视觉反馈直接关联状态变量无需额外事件总线。3.2 随机刷题Shuffle 后固定序列 无限重刷机制随机模式不等于“每次点都换题”而是首次加载时 shuffle 一次后续翻页沿该序列走避免用户反复刷到同一题。RandomView.vue初始化时调用const { shuffledQuestions } useQuestionBank() const questionList ref([]) const currentIndex ref(0) onMounted(() { // 只在 mounted 时生成一次随机序列 questionList.value shuffledQuestions.value })同时提供「重新随机」按钮触发新 shuffleconst reShuffle () { const arr [...allQuestions.value] for (let i arr.length - 1; i 0; i--) { const j Math.floor(Math.random() * (i 1)) [arr[i], arr[j]] [arr[j], arr[i]] } questionList.value arr currentIndex.value 0 }为什么不用Math.random()直接取因为单纯questions[Math.floor(Math.random() * len)]会导致重复题和概率偏差。Fisher-Yates shuffle 是标准算法确保每种排列等概率且序列长度固定方便用户预估刷题总量。3.3 错题重练localStorage 读写 题目去重 空状态兜底MistakeView.vue的核心是安全读取mistakeIds并过滤题库const { allQuestions, mistakeIds } useQuestionBank() const mistakeQuestions computed(() { if (mistakeIds.value.length 0) return [] return allQuestions.value.filter(q mistakeIds.value.includes(q.id)) }) // 清空错题记录 const clearMistakes () { mistakeIds.value [] localStorage.setItem(mistakeIds, []) }UI 层需处理三种状态mistakeQuestions.length 0显示「暂无错题快去刷题吧」mistakeQuestions.length 0正常渲染题目列表某些错题 ID 在题库中已不存在如题库更新后filter()自动跳过无需额外校验提示localStorage存储的是字符串所以JSON.parse()和JSON.stringify()必须成对出现。项目中所有对mistakeIds的修改都通过响应式ref统一管理避免直接操作localStorage导致视图不同步。3.4 模拟考试倒计时 答题限制 提交后即时评分ExamView.vue引入useCountdown()composable 管理倒计时// src/composables/useCountdown.js import { ref, onUnmounted } from vue export function useCountdown(totalSeconds) { const remaining ref(totalSeconds) const timer ref(null) const start () { if (timer.value) clearInterval(timer.value) timer.value setInterval(() { remaining.value-- if (remaining.value 0) { clearInterval(timer.value) remaining.value 0 } }, 1000) } const stop () { if (timer.value) clearInterval(timer.value) } onUnmounted(() stop()) return { remaining, start, stop } }考试页面初始化即启动倒计时并禁用题目切换template div classexam-container div classtimer剩余 {{ formatTime(remaining) }}/div QuestionCard :questioncurrentQuestion :disabledisSubmitted submithandleAnswerSubmit / button clicksubmitExam :disabledisSubmitted {{ isSubmitted ? 已提交 : 交卷 }} /button /div /template script setup import { ref, computed } from vue import { useQuestionBank } from /composables/useQuestionBank import { useCountdown } from /composables/useCountdown import QuestionCard from /components/QuestionCard.vue const { getExamQuestions } useQuestionBank() const examQuestions ref(getExamQuestions()) const currentQuestionIndex ref(0) const userAnswers ref({}) // { q001: 0, q002: true } const isSubmitted ref(false) const { remaining, start } useCountdown(1800) // 30分钟 1800秒 start() const currentQuestion computed(() examQuestions.value[currentQuestionIndex.value]) const handleAnswerSubmit (answer) { userAnswers.value[currentQuestion.value.id] answer if (currentQuestionIndex.value examQuestions.value.length - 1) { currentQuestionIndex.value } } const submitExam () { isSubmitted.value true // 计算得分遍历 examQuestions 与 userAnswers 对比 const score examQuestions.value.reduce((sum, q) { const userAns userAnswers.value[q.id] return sum (userAns q.answer ? 1 : 0) }, 0) // 显示结果弹窗此处省略 UI 组件 showResult(score, examQuestions.value.length) } /script参数说明useCountdown(1800)创建 30 分钟倒计时isSubmitted控制按钮禁用与题目交互锁定userAnswers用对象存储答案键为question.id避免数组索引错位。提交后reduce一次性比对所有答案时间复杂度 O(n)比逐题校验更高效。4. 打包部署与微信公众号 H5 嵌入适配要点4.1 构建产物优化Vue CLI 配置静态资源路径与跨域代理项目使用 Vue CLI默认构建输出到dist/。为适配微信公众号内嵌需确保资源路径正确// vue.config.js module.exports { publicPath: process.env.NODE_ENV production ? /your-project-name/ // 微信公众号配置的网页授权域名子路径 : /, devServer: { proxy: { /api: { target: http://localhost:3000, // 开发时指向 mock server可选 changeOrigin: true, pathRewrite: { ^/api: } } } }, configureWebpack: config { if (process.env.NODE_ENV production) { // 移除 console生产环境 config.optimization.minimizer[0].options.terserOptions.compress.drop_console true // 分离 vendor chunk提升首屏加载 config.optimization.splitChunks { chunks: all, cacheGroups: { vendor: { name: chunk-vendors, test: /[\\/]node_modules[\\/]/, priority: 10, chunks: initial } } } } } }注意publicPath必须与微信公众号后台设置的「JS 接口安全域名」及「网页授权域名」一致。若部署在https://example.com/h5/exam/则publicPath应设为/h5/exam/否则index.html中的js/app.xxx.js会 404。4.2 微信 H5 兼容性补丁解决 iOS Safari 缓存与 UA 识别问题微信内置浏览器基于 WKWebView但存在两处典型问题iOS Safari 强缓存index.html导致更新后用户仍看到旧版解决方案在index.htmlhead中添加meta http-equivCache-Control contentno-cache, no-store, must-revalidate / meta http-equivPragma contentno-cache / meta http-equivExpires content0 /微信 UA 无法被 Vue Router history 模式正确识别导致路由跳转白屏解决方案强制降级为 hash 模式并在router/index.js中import { createRouter, createWebHashHistory } from vue-router const router createRouter({ history: createWebHashHistory(), // 不用 createWebHistory() routes: [ { path: /, component: SequentialView }, { path: /random, component: RandomView }, { path: /mistakes, component: MistakeView }, { path: /exam, component: ExamView } ] })提示hash 模式 URL 形如https://example.com/#/exam虽不如 history 模式美观但在微信中 100% 兼容。若坚持用 history需 Nginx 配置try_files $uri $uri/ /index.html;但微信中仍偶发白屏不推荐。4.3 微信 JS-SDK 初始化获取定位、分享等能力按需启用标题未要求定位但热词中含「uniapp开发h5嵌入微信公众号中获取定位」说明用户有扩展需求。本项目预留 SDK 初始化入口// src/utils/wechatSDK.js export function initWechatSDK() { return new Promise((resolve, reject) { if (typeof window.WeixinJSBridge undefined) { document.addEventListener(WeixinJSBridgeReady, () resolve(window.WeixinJSBridge), false) } else { resolve(window.WeixinJSBridge) } }) } // 在需要调用定位的页面如某道地理题中 import { initWeixinSDK } from /utils/wechatSDK const getLocation async () { const wx await initWeixinSDK() wx.invoke(getLocation, { type: wgs84 // 返回 GPS 坐标 }, res { console.log(经纬度:, res.latitude, res.longitude) }, err { console.error(定位失败:, err) }) }注意调用前必须完成签名验证后端提供jsapi_ticket和nonceStr等参数本项目因“无后端”故仅提供调用框架。实际部署时需由业务方补充签名接口或使用第三方服务如腾讯云云函数生成 signature。5. 本地调试技巧与常见报错排查表5.1 本地运行时题库加载失败检查 JSON 格式与路径大小写最常见错误是Failed to fetch或Cannot find module /assets/data/questions.json。排查步骤现象原因解决方案Module not found: Error: Cant resolve /assets/data/questions.json路径拼写错误或文件未放在src/assets/data/下检查文件真实路径确认questions.json在src/assets/data/且 import 路径为/assets/data/questions.json指向src/Unexpected token in JSON at position 0服务器返回 HTML如 404 页面而非 JSON运行npm run serve后访问http://localhost:8080/src/assets/data/questions.json确认能直接下载 JSON 文件若返回 HTML说明 Webpack 未正确处理静态资源需检查vue.config.js中publicPath是否影响静态资源路由JSON 解析失败如SyntaxError: Unexpected token , in JSON at position 123JSON 文件末尾多逗号、中文引号、BOM 头用 VS Code 打开 JSON安装「Prettier」插件格式化右下角确认编码为 UTF-8 无 BOM删除最后一行多余逗号5.2 四种模式切换后状态残留响应式 ref 未重置例如从「模拟考试」退出后再进「顺序刷题」发现进度条卡在 30%或错题记录未清空。根本原因是多个模式共用同一份mistakeIds或currentIndex但未在路由切换时重置。解决方案在router/index.js中添加路由守卫router.beforeEach((to, from, next) { // 进入新模式前重置全局状态 if (to.name ! from.name) { // 重置错题 ID 列表仅当进入非错题页时 if (to.name ! MistakeView) { localStorage.setItem(mistakeIds, []) } // 重置当前题索引各模式独立维护 // 实际项目中应将 currentIndex 放入各模式组件内部而非全局共享 } next() })更优实践将currentIndex、userAnswers等状态封装在对应 View 组件内部如SequentialView.vue自己定义ref避免跨模式污染。本项目源码若未如此设计则需手动修复——这是“无后端”项目最容易忽视的状态隔离问题。5.3 微信中点击按钮无反应iOS 事件绑定失效部分 iOS 微信版本中click在button上不触发尤其当按钮内含纯文本无 padding 时。临时修复 CSS/* src/assets/styles/wechat-fix.css */ .wechat-button { -webkit-tap-highlight-color: transparent; -webkit-touch-callout: none; -webkit-user-select: none; }并在按钮上添加类button classwechat-button clicksubmitExam交卷/button原理-webkit-tap-highlight-color: transparent移除点击高亮-webkit-user-select: none防止误触选中文字。这是微信 H5 开发的必备样式补丁不影响其他平台。最后验证四种模式是否真正独立打开开发者工具 → Application → Local Storage → 查看mistakeIds是否只在答错时增加切换模式后location.hash是否准确反映当前路径模拟考试提交后localStorage中是否新增examResult记录如有。一切状态变更都应能在 DevTools 中实时观测这才是“无后端”应用可调试性的底线。本文还有配套的精品资源点击获取