Reputation: 3444
Don't know how to use v-model
on input checkbox type from a loop of a nested element.
I have successfully used a select/dropdown:
<select class="custom-select custom-select-sm" v-model="slide.filterCat">
<option :value="item.category" v-for="(item,index) in categories.elCats" :key="index">{{item.category}}</option>
</select>
It returns the item and models it correctly when updated,
however I would need to offer several options that can be selected and trying to use checkboxes instead.
The loop works fine and all labels and checkboxes are being shown correctly.
But I have no idea on how I can use simple v-model here.
I have used a method that checks if value is in array and if so to return true,
which works by using binding on :checked
:checked="isInCategoryList(item.category, slide.filterCat)
and the method:
isInCategoryList(curEl, list){
console.log(curEl);
console.log(list);
return list.includes(curEl ) ? true : false
},
But it logs an insane amount, which makes me think the approach is definitely not the correct one, for every event (mouseover,...) it keeps logging data.
And this snippet simply didn't work:
<div v-for="(item,index) in categories.elCats" :key="index">
<label>{{item.category}}</label>
<input type="checkbox" :value="item.category"
v-model="slide.filterCat">
</div>
Any guidance please...
Upvotes: 1
Views: 1246
Reputation: 37763
Multiple checkboxes (as well as <select multiple>
) requires the v-model
argument to be an array...
const vm = new Vue({
el: '#app',
data() {
return {
selected: [],
categories: [{
name: 'Category A',
value: 'A'
},
{
name: 'Category B',
value: 'B'
},
{
name: 'Category C',
value: 'C'
},
]
}
}
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flexboxgrid/6.3.1/flexboxgrid.min.css" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="row around-xs">
<div>
<h4>Checkboxes:</h4>
<div v-for="(item,index) in categories" :key="index">
<label>{{item.name}}</label>
<input type="checkbox" :value="item.value" v-model="selected">
</div>
</div>
<div>
<h4>Multi-select (using same model):</h4>
<select v-model="selected" multiple>
<option :value="item.value" v-for="(item,index) in categories" :key="index">{{item.name}}</option>
</select>
</div>
</div>
<h3>
Result: {{ selected }}
</h3>
</div>
Upvotes: 3