Reputation: 746
I am working an edit form, it happens that I have several options to choose, these options are obtained by ajax with axios and I assign them to the variable permisos
of the component that later renders through a v-for, the checked elements I have them in a array selected
that is assigned to the vue-model as follows
<div class="row">
<div v-for="permiso in permisos" class="col-md-5 col-12 col-sm-5" >
<input type="checkbox" :value="permiso.id"
class="form-control" :id=permiso.id
v-model="selected" :checked=selected.filter(e => e.id === permiso.id).length > 0 > {{ permiso.name}}
</div>
</div>
later I make another ajax call to know what options I had before editing the item to know what options or checkbox I will assign the checked attribute, this is where I have problems do not check correctly.
axios.get('api/allpermisos')
.then(response =>{
this.permisos = response.data; //dataok
})
if(this.action===2){
axios.get('api/allpermisos/'+ this.dataobject.id)
.then(response =>{
this.selected = response.data;//data ok
})
}
How can I do so that when I get the ajax call from the options already selected, the attribute checked is assigned automatically and those that are not, are not assigned. try with includes but I do not have the desired result?
The code works correctly if I remove the v-model. Why is this happening?
<input type="checkbox" :value="permiso.id" class="form-control"
:id=permiso.id :checked=selected.filter(e => e.id === permiso.id).length > 0 > {{ permiso.name}}
Upvotes: 0
Views: 6491
Reputation: 28992
You don't need both v-model and :checked. v-model is a two way binding.
https://jsfiddle.net/bbsimonbb/eywraw8t/15613/
<div v-for="permiso in permisos" class="col-md-5 col-12 col-sm-5" >
<input type="checkbox" :value="permiso.id"
class="form-control" :id=permiso.id
v-model="selected"> {{ permiso.name}}
</div>
Consider creating a component for your input. Form inputs inside a v-for rapidly gets complicated.
Upvotes: 4
Reputation: 3653
You need to keep their ids in "selected" array, you are probably keeping whole objects which didn't work from what I checked.
HTML:
<div id="app">
<div class="row">
<div v-for="permiso in permisos" class="col-md-5 col-12 col-sm-5" >
<input type="checkbox" :value="permiso.id"
class="form-control" :id=permiso.id
v-model="selected" :checked=selected.includes(permiso.id)> {{ permiso.name}}
</div>
</div>
</div>
Vue:
new Vue({
el: '#app',
data() {
return {
selected: [2, 4],
permisos: [{id: 1, name: "test1"}, {id: 2, name: "test2"}, {id: 3, name: "test3"}, {id: 4, name: "test4"}]
}
}
})
https://jsfiddle.net/eywraw8t/15555/
This works. If you are getting object array as response, you could do this:
this.selected = response.data.map(obj => obj.id);
Upvotes: 3