Vue.js how to use radio buttons inside v-for loop

2020-04-15 01:35发布

I'm trying to use radio buttons, so that users can choose one of the photos as their profile photo:

<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>

The values are otained like this:

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);
  })
},

When an photo is chosen, the profileImg variable should be set to that photo's imgId.

The problem is how to let users to choose only one photo as profile image inside this v-for loop?

Update: a photo my myPhotos object that I'm iterate over:

enter image description here

标签: vue.js
2条回答
成全新的幸福
2楼-- · 2020-04-15 02:25

By providing name you can treat it as one element

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>

查看更多
我只想做你的唯一
3楼-- · 2020-04-15 02:32

How about setting name attribute for the input field

 <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>
查看更多
登录 后发表回答