Rakesh K
Rakesh K

Reputation: 1330

How to bind(v-model) data when a list with radio buttons in each list in Vue JS

I am fetching data from API. My data looks like -

    [
     {
    id:1,
    name:nameOfTheGroup1,
    participants:[
                   {   
                    id:1,
                    name:participant1
                   },
                   {   
                    id:2,
                    name:participant2
                   }
                 ]
     },
     {
    id:2,
    name:nameOfTheGroup2,
    participants:[
                   {   
                    id:3,
                    name:participant1
                   },
                   {   
                    id:4,
                    name:participant2
                   }
                 ]
    }
  ]

As you can see its an array of objects. and in each object has nested array of objects. Basically i am trying to fetch all the groups for current user with its participants.

Now i am showing those in the browser using v-for like this -

  <h3>Please assign an admin to given groups</h3>

  <div v-for="group in groups">
    {{ group.name }}

    <div v-for="participant in group.participants">
      <input type="radio" value="" v-model=""/>
      <label>{{ participant.name }} </label>
   </div>

   </div>

Now, my question is how can i bind this data using v-model to get object/array with

group id and assigned user (radio checked ).

This is my best how i could explain))

Thanks.

Upvotes: 2

Views: 2221

Answers (2)

Skipper
Skipper

Reputation: 396

First of all, your model doesn't have any field for the assigned participant. So, you need to add something like that:

   id:1,
    name:'nameOfTheGroup1',
    assignedId: '',
    participants:[
                   {   
                    id:1,
                    name:'participant1'
                   },
                   {   
                    id:2,
                    name:'participant2'
                   }
                 ]
     },
     {
    id:2,
    name:'nameOfTheGroup2',
    assignedId: 3,
    participants:[
                   {   
                    id:3,
                    name:'participant1'
                   },
                   {   
                    id:4,
                    name:'participant2'
                   }
                 ]

Then you need to provide binding:

    <div v-for="participant in group.participants">
      <input type="radio" v-model="group.assignedId" :value="participant.id" :name="group.id"/>
      <label>{{ participant.name }} </label>
   </div>

Do not forget to add "name" attribute to the radio.

Working example is here https://jsfiddle.net/7x46mtr1/

Upvotes: 1

Radu Diță
Radu Diță

Reputation: 14211

Try to use a property on participant. Something like this

v-model=“participant.status”

Upvotes: 0

Related Questions