如何为一组动态创建的单选按钮使用标签?

时间:2018-02-28 22:57:01

标签: vuejs2

我在Vuejs 2中有一个动态创建的单选按钮列表:

<div class="form-check" v-for="design in designs" :key="design.id">
                    <input class="form-check-input" type="radio" :value="design" v-model="selectedDesign" :id="design.id" :name="design.id">
                    <label class="form-check-label" v-bind:for="design.id">{{design.name}}</label>
                  </div>

然而,“v-bind:for”不起作用 - 并且对“for”进行硬编码不会让我链接到动态创建的单选按钮。 有谁知道如何在动态创建的标签中使用“for”?

1 个答案:

答案 0 :(得分:0)

您的代码段有效。

仔细检查元素的ID,您可能有重复的ID,导致label出现故障。

查看下面的演示。有两个无线电可以工作(所以你知道你的代码片段有效)和一个没有无线电有效(因为有一个重复:<div>与无线电相同的id

new Vue({
  el: '#app',
  data: {
    designs: [
      {id: 1, name: "I'm the label for the radio with id=1 (will work)"},
      {id: 2, name: "I'm the label for the radio with id=2 (won't work because another element with id=2 exists)"},
      {id: 3, name: "I'm the label for the radio with id=3 (will work)"}
    ],
    selectedDesign: null
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script>

<div id="app">
  <div id="2">I am a div with id=2.</div>
  <br><br>
  <div class="form-check" v-for="design in designs" :key="design.id">
    <input class="form-check-input" type="radio" :value="design" v-model="selectedDesign" :id="design.id" :name="design.id">
    <label class="form-check-label" v-bind:for="design.id">{{design.name}}</label>
  </div>
  
</div>