1

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
    },
]```
Milad Dastan Zand
  • 1,062
  • 1
  • 10
  • 21
  • 2
    https://stackoverflow.com/questions/42133894/vue-js-how-to-properly-watch-for-nested-data – Djave Nov 10 '21 at 11:36
  • Don't watch the checkbox at all. Watch the variable that controls the checkbox's state. When working in modern SPA frameworks it's best to think of the DOM as a side-effect representation of your application's data. – Daniel Beck Nov 10 '21 at 13:37

1 Answers1

1

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)
  })
}
Amaarockz
  • 4,348
  • 2
  • 9
  • 27