I create some dynamic checkboxes with vue and they look like this;
<li v-for="element in checklist" :key="element.id" class="block w-full p-1">
<div v-if="element.taskId == task" class="w-full border-2 rounded-md p-4">
<div class="float-right">
<button @click="deleteCheck(element.id)">
<Trash2Icon class="px-1"/>
</button>
</div>
<div class="flex">
<input type="checkbox" id="checkbox" v-model="element.checked" class="w-6">
<label for="checkbox" class="px-2">{{element.content}}</label>
</div>
</div>
</li>
I want to watch "element.checked" value with watch() function in vue and I want to post it to API with using axios. and its looks maybe like this;
watch: {
element.checked() { // doesn't work
axios.put('api/blabla' element.id, // I'm not sure here, I'm just trying to compare
checked: this.element.checked
})
.catch(err => {
console.log(err)
})
}
}
I'm just looking for a method, it could be different. the above code is just a guess element.checked is gives an error.
btw my checklist looks like;
"checklist": [
{
"content": "lorem ipsum dolor",
"checked": true,
"id": 1
},
{
"content": "lorem ipsum dolor sit",
"checked": false,
"id": 2
},
]```
CodePudding user response:
You don't need to use a watch here...all you need to do is bind a @change
event like
<input type="checkbox" id="checkbox" v-model="element.checked" @change="customMethod" class="w-6">
and in methods
methods: {
customMethod() {
axios.put('api/blabla' element.id,
checked: this.element.checked
})
.catch(err => {
console.log(err)
})
}