Vue3 问答应用最后一题按钮文本无法更新为Finish求助
问题分析与修复方案
核心问题
按钮文本无法更新为Finish的原因是判断条件错误:你在按钮中使用getCurrentQuestion.index来判断是否是最后一题,但这个index属性根本不存在,属于错误取值。
具体修复步骤
修正按钮判断逻辑
直接用currentQuestion.value(当前题目的索引)判断是否到达最后一题,替换原来无效的getCurrentQuestion.index判断。清理无效代码
- 删除
getCurrentQuestion计算属性中错误的questions.index = question.value代码:question是数组中的对象,没有value属性,这行代码完全无效。 - 删除
nextQuestion函数中报错的console.log(currentQuestion.index, value):currentQuestion是ref对象,没有index属性,value也未定义。 - 删除
setAnswer函数中多余的evt.target.value = null:v-model已经绑定选中值,手动修改input value会导致逻辑混乱。
- 删除
额外优化
将input的:name属性改为question-${currentQuestion.value},避免不同题目之间的radio组冲突。
修改后的完整代码
<script setup> import { ref, computed } from 'vue' const questions = ref([ { question: 'How many books are in the kjva bible?', answer: 0, options: [ '80', '32', '60', ], selected: null }, { question: "What is the name of Israel's first king?", answer: 2, options: [ 'David', 'Asa', 'Saul', ], selected: null }, { question: 'Salvation is of the...?', answer: 1, options: [ 'Egyptians', 'Jews', 'Edomites', ], selected: null } ]) const quizCompleted = ref(false) const currentQuestion = ref(0) const score = computed(() => { let value = 0 questions.value.map(q => { if(q.selected == q.answer) { value++ } }) return value }) const getCurrentQuestion = computed(() => { return questions.value[currentQuestion.value] }) const setAnswer = evt => { questions.value[currentQuestion.value].selected = evt.target.value } const nextQuestion = () => { if(currentQuestion.value < questions.value.length -1) { currentQuestion.value++ console.log('当前题目索引:', currentQuestion.value); console.log('总题目数:', questions.value.length); } else { quizCompleted.value = true console.log('Quiz Completed') } } </script> <template> <main class="app"> <h1>The Quiz</h1> <section class="quiz"> <div class="quiz-info"> <div class="question">{{ getCurrentQuestion.question }}</div> <div class="score">Score {{ score }}/{{ questions.length }}</div> </div> <div class="options"> <label v-for="(option, index) in getCurrentQuestion.options" :key="index" :class="`option ${ getCurrentQuestion.selected == index ? index == getCurrentQuestion.answer ? 'correct' : 'wrong' : '' } ${ getCurrentQuestion.selected != null && index != getCurrentQuestion.selected ? 'disabled' : '' }`"> <input type="radio" :name="`question-${currentQuestion.value}`" :value="index" v-model="getCurrentQuestion.selected" :disabled="getCurrentQuestion.selected" @change="setAnswer" /> <div>{{ option }}</div> </label> </div> <button @click="nextQuestion" :disabled="!getCurrentQuestion.selected"> {{ currentQuestion.value == questions.length - 1 ? 'Finish' : getCurrentQuestion.selected == null ? 'Select an option' : 'Next Question' }} </button> </section> </main> </template> <style scoped> * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Montserrat', sans-serif; } body { background-color: #271C36; color: #fff; } </style>
内容的提问来源于stack exchange,提问作者Brandon Howard
相关产品推荐
相关产品推荐

