Search code examples
javascriptarraysvue.jscheckboxlist

How to use v-for 2 times to get specific values in check-box action form?


I am new to Vue js. I am trying to do an action form for the rest of API. I don't know how to get the data of name and location only. I was trying to use slice in Array, but it does not work.

My action form:

<div class="form-group">
   <label class="required"> Social Media </label>
   <b-form-checkbox  v-for="event in events" :key="event._id" :value="event" v-model="selected">
               {{event.name}}, {{event.location}}
   </b-form-checkbox>
   <span class="mt-3">Selected: <strong>{{ selected }}</strong></span>
</div>

My Vue instance

export default {
    data() {
        return {     
            events: [{
                 "_id": "d4d81da6-b453-4a31-999f-a2ea04848ee9",
                 "name": "A",
                 "location": "US",
                 "__v": 0
                 },
                 {
                 "_id": "91205d34-4480-4e4e-bdf7-fe66e46922b0",
                 "name": "B",
                 "location": "Korea",
                 "__v": 0
                 },
                 {
                 "_id": "0b168c44-4f38-4f86-8ee6-e077333aca95",
                 "name": "C",
                 "location": "Japan",
                 "__v": 0
                 }],
           selected: ''
                 
        };
    }
}

The Output when checking the first option of the checkbox:

Selected: ["_id": "d4d81da6-b453-4a31-999f-a2ea04848ee9", "name": "A", "location": "US", "__v": 0]

Expected output when checking the first option of the checkbox:

Selected: [ "name": "A", "location": "US" ]

Solution

  • You can create the necessary structure within the :value="" assignment.

     <b-form-checkbox  v-for="event in events" :key="event._id" :value="{ name: event.name, location: event.location }" v-model="selected">
        {{event.name}}, {{event.location}}
     </b-form-checkbox>