Vue.js测验应用如何保存每道题复选框状态并实现答案正确性校验
核心问题
你当前出现状态错乱的核心原因有两个:
- 所有题目共用同一个一维数组
checkedAnswers存储选中状态,切换题目时复用了相同下标的状态值 - 复选框的
id属性直接用了answer.title,不同题目如果有相同选项会出现id重复,导致label和复选框关联错乱
改造方案
1. 调整状态存储结构
将checkedAnswers改为二维结构,按题目索引+选项索引两级存储选中状态,保证每道题的选中结果独立保存。
首先修改getQuestions方法,拿到题目列表后初始化每道题的空选中数组:
async getQuestions() { this.loading = true; let response = await fetch("http://localhost:4000/test"); let jsonResponse = await response.json(); this.questions = jsonResponse.questions; // 初始化每道题的选中状态数组 this.checkedAnswers = this.questions.map(() => []); this.loading = false; },
2. 修正模板绑定逻辑
修改复选框的v-model、id、label for属性,关联当前题目索引避免冲突:
<li v-for="( answer, key ) in currentQuestion.answers" :key="`q${index}_a${key}`" > <input v-model="checkedAnswers[index][key]" @change="answerClick" :id="`q${index}_a${key}`" type="checkbox" /> <label :for="`q${index}_a${key}`" >{{ answer.title }}</label> </li>
3. 补充End按钮校验逻辑
新增提交校验方法,遍历所有题目对比用户选中结果和正确答案:
首先给End按钮绑定点击事件:
<a class="ctlBtn" @click="submitTest">End</a>
然后在methods里添加校验逻辑:
submitTest() { let correctCount = 0; this.questions.forEach((question, qIndex) => { // 拿到当前题目用户选中的选项索引 const userSelected = this.checkedAnswers[qIndex] .map((checked, aIndex) => checked ? aIndex : null) .filter(v => v !== null); // 拿到当前题目正确选项的索引 const correctAnswers = question.answers .map((ans, aIndex) => ans.correct ? aIndex : null) .filter(v => v !== null); // 多选题要求选中的和正确的完全一致才算对,可根据需求调整判分规则 const isCorrect = userSelected.length === correctAnswers.length && userSelected.every(v => correctAnswers.includes(v)); if (isCorrect) correctCount++; }); // 可自定义结果展示逻辑 alert(`答题完成,共${this.questions.length}题,答对${correctCount}题`); }
可选补充:Restart按钮重置逻辑
如果需要重置功能,给Restart按钮绑定对应方法即可:
restartTest() { this.index = 0; this.checkedAnswers = this.questions.map(() => []); }
内容的提问来源于stack exchange,提问作者vuenobo
相关产品推荐
相关产品推荐

