默认情况下未选中Vue.js单选按钮

时间:2018-10-25 06:59:11

标签: vue.js radio-button

我想在v-for循环中选中默认的单选按钮。 这是代码:

  <ul v-for="p in photos">
        <li>
          <div>

          <div>
            <div>
              Visibility: {{p.visible}}
            </div>                


            <strong>Visibility setting</strong><br>
            <input type="radio" v-model="p.visible" name="visibility" value="all" :checked="p.visible == 'all'"> All <br>
            <input type="radio" v-model="p.visible" name="visibility" value="fav" :checked="p.visible == 'fav'"> My favorites <br>
            <input type="radio" v-model="p.visible" name="visibility" value="none" :checked="p.visible == 'none'"> No one

          </div>
            <div><img" v-bind:src="BASE_URL +'/uploads/' + userId + '/'+ p.imgId" /> </div>
        </div>          


      </li>

      </ul>

我遵循了this的答案。

虽然我可以看到正在打印每一项的Visibility,但是并未按预期检查每张照片的默认单选按钮。

这是创建组件时从服务器收到的photos数组:

   [ 
        {
            "id" : "5bcebb6efeaea3147b7a22f0",
            "imgId" : "12710.png",
            "visible" : "all"
        }, 
        {
            "id" : "5bcebbf0feaea3147b7a22f1",
            "imgId" : "62818.png",
            "visible" : "fav"
        }, 
        {
            "id" : "5bcec010feaea3147b7a22f2",
            "imgId" : "36740.png",
            "visible" : "none"
        }
    ],

这里有什么问题,我该如何解决?

1 个答案:

答案 0 :(得分:4)

Don't use :checked

  

v-model将忽略在任何表单元素上找到的初始valuecheckedselected属性。它将始终将Vue实例数据视为事实的来源。您应在组件的data选项内的JavaScript端声明初始值。

如果v-modelvalue相同,则该复选框将返回true。您的固定小提琴:

new Vue({
  el: '#app',
  data: {
    photos: [{
        "id": "5bcebb6efeaea3147b7a22f0",
        "imgId": "12710.png",
        "visible": "all"
      },
      {
        "id": "5bcebbf0feaea3147b7a22f1",
        "imgId": "62818.png",
        "visible": "fav"
      },
      {
        "id": "5bcec010feaea3147b7a22f2",
        "imgId": "36740.png",
        "visible": "none"
      }
    ],
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">

  <ul v-for="(p, index) in photos">
    <li>

      <div>
        Visibility: {{p.visible}}
      </div>

      <strong>Visibility setting</strong><br>
      <input type="radio" v-model="photos[index].visible" :name=`visibility-${index}` value="all"> All <br>
      <input type="radio" v-model="photos[index].visible" :name=`visibility-${index}` value="fav"> My favorites <br>
      <input type="radio" v-model="photos[index].visible" :name=`visibility-${index}` value="none"> No one

    </li>
  </ul>



</div>

现在,每个广播组都有自己的name,其中v-model定位到该组(请注意index)。