Vue.js如何在v-for循环中使用单选按钮

时间:2018-10-23 07:08:21

标签: vue.js

我正在尝试使用单选按钮,以便用户可以选择其中一张照片作为其个人资料照片:

<ul v-for="p in myPhotos">
  <li>
    <div>
      <div>
        <div>
          photo id: {{p.imgId}}
        </div>
        <input type="radio" v-model="profileImg" value="p.imgId"> Choose as profile image
      </div>
      <div><img v-bind:src="BASE_URL +'/uploads/' + userId + '/'+ p.imgId" /> </div>
    </div>
  </li>
</ul>

这样获得值:

created () {
  axios.get(this.BASE_URL + '/profile/g/myphotos/', this.jwt)
  .then( res => {
    this.myPhotos = res.data.photos;
    this.showUploadedPhoto = true;
    this.profileImg = res.data.profileImg
  })
  .catch( error => {
    console.log(error);
  })
},

选择照片后,profileImg变量应设置为该照片的imgId。

问题是如何让用户在此v-for循环中仅选择一张照片作为个人资料图像?

更新:将我的myPhotos对象迭代的照片:

enter image description here

2 个答案:

答案 0 :(得分:3)

通过提供名称,您可以将其视为一个元素

var app = new Vue({
  el:"#app",
  data:{
    images:[{imgId:1},{imgId:2},{imgId:3}],
    profileImg:2
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
  <div v-for="image in images">
              <input type="radio" v-model="profileImg" name="profileImg" :value="image.imgId"> Choose as profile image
  </div>
  You have selected : {{profileImg}}
 </div>
</div>

答案 1 :(得分:1)

如何为输入字段设置name属性

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

      <div>
        <div>
          photo id: {{p.imgId}}
        </div> 
          <input type="radio" name="user_profile_photo" v-model="profileImg" :value="p.imgId"> Choose as profile image
      </div>
        <div><img v-bind:src="BASE_URL +'/uploads/' + userId + '/'+ p.imgId" /> </div>
    </div>
      </li>

  </ul>