Search code examples
vue.jscheckboxnuxt.jsv-model

add checkboxs values to data array in nuxt


I am using nuxt v2.15

Those are my checkboxes:

<div v-for="category in categories" v-bind:key="category.id" class="ml-4">
  <input type="checkbox" name="categories[]" @change="search()" v-model="form.categories" :id="`category`+category.id" :value="category.id">
  <label :for="`category`+category.id">{{ category.title }}</label>
</div>

When I check one of them, form.categories becomes true! The value of the checkbox is not added to the form.categories array.

It should store values of checkboxes (category.id) in form.categories but instead it toggles form.categories to true and false state.

How can I store checkbox values inside form.categories?

PS: I have a project with older version of Nuxt and this is working fine! But in the new project this is not working. Is it because of a newer version?


Solution

  • i solve it by writing a function to add category.id into form.categories :

    addCategory (id) {
      if(!this.form.categories.includes(id))
         this.form.categories.push(id);
      else
         this.form.categories.splice(this.form.categories.indexOf(id), 1);
      this.search()
    

    }

    i call it in checkbox @change