我正在VueJS中创建一个表单,该表单允许用户使用各种问题类型来创建测验。这些问题类型之一是多项选择。目前,这是我用于新测验的数据结构。
newQuiz: {
title: '',
questions: [
],
}
这是多项选择题的结构...
this.newQuiz.questions.push({
id: count+'mc',
type: 'mc',
question: 'Example',
correct: 0,
answers: [
'First answer',
'Second answer',
'Third answer',
'Fourth answer'
]
});
当前,我在一个div上运行一个v-for
,该div会创建每个问题,并为单选按钮提供适当的标签,名称等。每个单选按钮及其相应的标签都有一个运行的@click
这样的功能...
this.newQuiz.questions[question].correct = answer;
我很好奇是否可以将单选按钮绑定到正确的值,以便不需要更新功能,或者是否可以正确显示默认值?
对于上下文,这也是v-for
。
<div v-for="(question, qIndex) in this.newQuiz.questions" :key="question.id">
<div v-if="question.type='mc'" class="mb-8">
<label class="block">{{ question.question }}</label>
<div v-for="(answer, aIndex) in question.answers" :key="answer">
<input type="radio" :id="question.id+'-'+aIndex" :name="question.id" @click="updateMCAnswer(qIndex, aIndex)">
<label :for="question.id+'-'+aIndex" @click="updateMCAnswer(qIndex, aIndex)">{{ answer }}</label>
</div>
</div>
</div>
答案 0 :(得分:3)
如果要将答案直接绑定到相应问题的correct
字段,请尝试以下代码
<div v-for="(question, qIndex) in this.newQuiz.questions" :key="question.id">
<div v-if="question.type='mc'" class="mb-8">
<label class="block">{{ question.question }}</label>
<div v-for="(answer, aIndex) in question.answers" :key="answer">
<input type="radio" :id="question.id+'-'+aIndex" :name="question.id" v-model="question.correct"
:value="answer">
<label :for="question.id+'-'+aIndex" @click="updateMCAnswer(qIndex, aIndex)">{{ answer }}</label>
</div>
</div>
</div>
您可以删除click
事件并通过将v-model="question.correct"
和:value="answer"
添加到input
字段来直接绑定值。