I have 2 arrays one for possible checkbox variants and one for already saved-checked boxes.VUEJS template for example
<ul>
<li v-for="cit in possable">
<label>
<input
type="checkbox"
:checked="savedcbx.indexOf(+cit.id)>-1"
:value="cit.id"/>
{{cit.rname}}
</label>
</li>
</ul>
And my question about how add new checkedbox to saved array or delete from saved array uncheckedbox&
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With