1

How can i use b-form-checkbox inside v-for

this is my code

<div v-for="(user, index) in users" :key="index">
<b-form-checkbox name="check-button" switch>
</b-form-checkbox>
</div>

how can i pass user id and checkbox value into a method when i switch checkbox. Each checkbox have different user id

Anyone can help me, thanks in advance

2 Answers 2

4

Check out example 2 at https://bootstrap-vue.js.org/docs/components/form-checkbox/

Checkboxes – selected values (in this case the user's id) will be elements of the selected array because it's the v-model for the checkbox group. If a user id isn't in the array, it's not selected.

<b-form-group label="Users:">
  <b-form-checkbox-group id="checkbox-group" v-model="selected" name="selectedUsers">
    <b-form-checkbox v-for="(user, index) in users" :value="user.id" switch></b-form-checkbox>
  </b-form-checkbox-group>
</b-form-group>

Your component JS – there are a million ways to find out if a user is selected, below is an example method to see if a specific user id exists in the selected array.

data(){
  return {
    selected: []
  }
},
methods: {
  userIsSelected(userid){
    return this.selected.includes(userid)
  }
}

If you want to know when selection changes, you can watch the selected array:

data(){
  return {
    selected: []
  }
},
watch: {
  selected: {
    deep: true,
    handler: function(newValue){
      console.log("Selected users changed", newValue)
    }
  }
},
methods: {
  userIsSelected(userid){
    return this.selected.includes(userid)
  }
}

The deep property may or may not be necessary, but if your array ever includes objects or nested arrays it would be important.

Sign up to request clarification or add additional context in comments.

Comments

1

in case someone's still looking this is what I ended up doing.

if checkbox is ticked the current user object in the loop will be added to the selected [] array and removed when unticked so you can what you want in the changeMethod.

<div>
 <b-form-checkbox
    v-for="(user, index) in users"
    :key="index"
    v-model="selected"
    :value="user"
    name="checkbox"
    @change="changeMethod">
 </b-form-checkbox>
</div>

data(){
  return {
    selected: []
    users: [{
      name: 'user 1'
      id: '1'
     },...]
  }
},

methods: {
//handle what happens to your selected value when checkbox status changes
  changeMethod(){
    console.log(this.selected)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.