vuejs model for checkbox group vuejs model for checkbox group arrays arrays

vuejs model for checkbox group


You only need one array to achieve toggling. From the Arrays section of Vue.js docs:

HTML:

<div id='example-3'>  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">  <label for="jack">Jack</label>  <input type="checkbox" id="john" value="John" v-model="checkedNames">  <label for="john">John</label>  <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">  <label for="mike">Mike</label>  <br>  <span>Checked names: {{ checkedNames }}</span></div>

Vue app:

new Vue({  el: '#example-3',  data: {    checkedNames: []  }})


I just put savedcbx to model and it works like in answer above.Vue great thing.

             <ul>            <li v-for="cit in possable">                <label>                <input                      type="checkbox"                    v-model="savedcbx"                    //with model this not need too                     :checked="savedcbx.indexOf(+cit.id)>-1"                    :value="cit.id"/>                {{cit.rname}}                </label>            </li>        </ul>


So, assuming you have this data:

data() {  return {    possable: [1,2,3,4,5],    savedcbx: [3,4]   }}

If you want to add a new item into savedcbx you just have to push it into the array (make sure it doesn't exist already)

addSavedId (id) {  // Don't add it if it already exists  if(this.savedcbx.indexOf(id) !== -1) return;  this.savedcbx.push(id);}

To remove an item:

removeSavedId (id) {  let index = this.savedcbx.indexOf(id);  // Nothing to remove if item is not in array  if(index === -1) return;  // Remove `index`  this.savedcbx.splice(index, 1);}

And now it's up to you when you call the addSavedId(id) and removeSavedId(id) functions and what is the parameter id.