Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

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

like image 840
Babr Avatar asked Oct 23 '18 07:10

Babr


2 Answers

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>
like image 57
Niklesh Raut Avatar answered Oct 09 '22 04:10

Niklesh Raut


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>
like image 25
Nermin Avatar answered Oct 09 '22 06:10

Nermin