Vue 3答题应用checkAnswer方法未触发点击就提前执行问题排查
问题原因与修复方案
根因分析
checkAnswer方法未触发点击就提前执行,核心原因是你将该方法同时放在了v-bind:class的动态判断逻辑中:
<li ... :class="{'text-white bg-success' : checkAnswer(answer)}">{{answer}}</li>
Vue每次渲染模板、更新视图时,都会执行动态绑定的表达式计算最终属性值,所以页面初始化、数据更新触发重渲染时都会自动调用checkAnswer,和点击事件完全无关。
同时你当前的逻辑也不符合需求:只要是正确答案,哪怕用户没点击也会直接标绿,没有实现「点击后才判断对错」的交互逻辑。
修复方案
步骤1:新增响应式变量存储用户选中答案,切题时重置状态
在data配置中加selectedAnswer字段,同时在切题方法中补充重置逻辑:
data() { return { questionCount: 0, selectedAnswer: null, // 存储用户选中的答案 results: [/* 原有数据保持不变 */] }; }, methods: { nextQuestion() { if (this.questionCount < this.results.length - 1) { this.questionCount++; this.selectedAnswer = null; // 切题重置选中状态 } }, prevQuestion() { if (this.questionCount >= 1) { this.questionCount--; this.selectedAnswer = null; // 切题重置选中状态 } }, // 修改checkAnswer逻辑:点击时仅存储选中答案 checkAnswer(answer) { if (this.selectedAnswer) return; // 可选:禁止重复选择答案 this.selectedAnswer = answer; }, // 其余方法保持不变 }
步骤2:修改模板动态class绑定逻辑
不要在渲染阶段调用checkAnswer,改为通过选中状态判断样式:
<li v-for="answer in answers" @click="checkAnswer(answer)" :class="{ 'text-white bg-success': selectedAnswer === answer && answer === results[questionCount].correct_answer, 'text-white bg-danger': selectedAnswer === answer && answer !== results[questionCount].correct_answer }" > {{answer}} </li>
可选优化
你当前的shuffle方法会直接修改原始数组,建议在计算answers时先拷贝数组避免污染原始数据:
computed: { answers() { // 拷贝数组避免修改原有的incorrect_answers数据 let incorrectAnswers = [...this.results[this.questionCount]["incorrect_answers"]]; let correctAnswer = this.results[this.questionCount]["correct_answer"]; return this.shuffle(incorrectAnswers.concat(correctAnswer)); } }
内容的提问来源于stack exchange,提问作者Razvan Zamfir
相关产品推荐
相关产品推荐

