标签和单选按钮的Vue JS表单绑定

时间:2019-06-13 15:07:10

标签: javascript vue.js nuxt.js

我正在尝试生成一个表单列表,这些表单是根据数据动态轮询的。但是,使用:for或v-bind:for不会在浏览器中产生任何html标记,因此单击标签时,它们不会选择相对输入。我创建了一个JSFiddle(出于某种原因SCSS无法在JS Fiddle中工作)。该项目也是Nuxt构建。

代码: https://jsfiddle.net/mc4rdle/o19bgjpe/2/

标记:

<div class="option" v-for="answer in poll.answers" :key="answer.answer.id">
  <input type="radio" :id="answer.id" :value="answer.answer">
  <label class="option" :for="answer.id">
     <div class="indicator"></div>
     <div class="label">{{ answer.answer }}</div>
   </label>
</div>

数据: 民意调查:[

{
                    id: 1,
                    question: 'How do you feel about your current salary?',
                    answers: [
                        {
                            id: 1,
                            answer: 'Satisfied'
                        },
                        {
                            id: 2,
                            answer: 'Content'
                        },
                        {
                            id: 3,
                            answer: 'Unhappy'
                        }
                    ]
                },
                {
                    id: 2,
                    question: 'What group activity should we do??',
                    answers: [
                        {
                            id: 1,
                            answer: 'Yoga'
                        },
                        {
                            id: 2,
                            answer: 'Table Tennis'
                        },
                        {
                            id: 3,
                            answer: 'Pints'
                        }
                    ]
                }
            ]

预先感谢:)

1 个答案:

答案 0 :(得分:1)

您输入的ID是重复的,因为它仅基于答案的ID。您可以结合使用poll.id + '-' + answer.id

    <div class="option" v-for="answer in poll.answers" :key="answer.answer.id">
      <input type="radio" :id="poll.id + '-' + answer.id" :value="answer.answer" :name="poll.id">
      <label class="option" :for="poll.id + '-' + answer.id">
        <div class="indicator"></div>
        <div class="label">{{ answer.answer }}</div>
      </label>
    </div>

jsfiddle上的演示