Laravel+Vue测验App:未选选项时禁用Next按钮
Hey there! Let's sort out that Next button behavior for your Laravel + Vue quiz app. The goal is to keep the Next button disabled until the user picks at least one option for the current question—here's how to implement it smoothly:
Step 1: Update the Next Button with Disable Condition
Modify your Next button to include a :disabled binding that checks if the user has selected an option for the current question. We'll leverage your existing userResponses array, checking the value at the active questionIndex:
<div v-show="questionIndex!=questions.length"> <button class="btn btn-success" @click="next();postuserChoices()" :disabled="!userResponses[questionIndex]"> Next </button> </div>
Step 2: Optimize Radio Button Setup
Your radio input can be tweaked to make selection tracking clearer and avoid cross-question conflicts. Using choice.id as the value gives you a consistent, trackable selection, and adding a unique name prefix ensures each question's radio group stays isolated:
<li v-for="choice in question.answers" :key="choice.id"> <label> <input type="radio" :value="choice.id" :name="`question-${questionIndex}`" v-model="userResponses[questionIndex]" @click="choices(question.id, choice.id)"> {{ choice.answer }} </label> </li>
:name="question-${questionIndex}"ensures radio buttons from different questions don't interfere with each other.- Storing
choice.idinuserResponsesmakes it easier to process selections later (like checking against correct answers).
Step 3: Adjust Initial Data (Optional but Recommended)
Swap out the initial false values in userResponses for null—this makes it more explicit that the user hasn't made a selection yet (though false will still work if you prefer):
data() { return { questions: this.quizQuestions, questionIndex: 0, userResponses: Array(this.quizQuestions.length).fill(null), // Null = unselected state currentQuestion: 0, currentAnswer: 0, } },
How It Works
- When no option is selected,
userResponses[questionIndex]remainsnull(orfalse), so!userResponses[questionIndex]evaluates totrue—keeping the button disabled. - As soon as the user clicks a radio button,
v-modelupdatesuserResponses[questionIndex]to the selectedchoice.id, making!userResponses[questionIndex]evaluate tofalse—enabling the Next button.
This setup fits cleanly into your existing code structure. Let me know if you need to adjust anything for edge cases!
内容的提问来源于stack exchange,提问作者Daljit Singh

