首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在VueJS中绑定多选题答案

如何在VueJS中绑定多选题答案
EN

Stack Overflow用户
提问于 2020-04-07 05:08:35
回答 1查看 910关注 0票数 1

我正在用VueJS创建一个表单,该表单允许用户使用各种问题类型创建测验。其中一种问题类型是多项选择题。目前,这是我为新测验准备的数据结构...

代码语言:javascript
复制
newQuiz: {
   title: '',
   questions: [

   ],
}

这是多项选择题的结构。

代码语言:javascript
复制
this.newQuiz.questions.push({
    id: count+'mc',
    type: 'mc',
    question: 'Example',
    correct: 0,
    answers: [
        'First answer',
        'Second answer',
        'Third answer',
        'Fourth answer'
    ]
});

目前,我有一个在v-for上运行的div,它创建每个问题,为单选按钮提供适当的标签、名称等。每个单选按钮及其相应的标签都有一个运行函数的@click

代码语言:javascript
复制
this.newQuiz.questions[question].correct = answer;

我很好奇是否可以将单选按钮绑定到正确的值,这样就不需要更新功能,或者默认显示正确选择?

对于上下文,这里也有v-for

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-07 15:13:45

如果您希望将答案直接绑定到相应问题的correct字段,请尝试以下代码

代码语言:javascript
复制
    <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事件,并通过在input字段中添加v-model="question.correct":value="answer"来直接绑定值。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61069022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档