How to get array value from checkbox in vue js

Viewed 138

I just made a form to choose every needed check boxes. The checkbox value is gotten from api that I created. But when I try to choose it more than one, it just show the value that just chosen. How can I show every checkbox value that I've checked?

Here is my form. In my case, i used vuetify:

<v-list-tile v-for="check in checks" :key="check.menu_id">
 <v-list-tile-content>
  <v-checkbox
   :key="check.menu_id"
   v-model="form.data.menu_id"
   :value="check.menu_id"
   :label="check.name"
  >
  </v-checkbox>
 </v-list-tile-content>
</v-list-tile>

And here is the script:

data: function () {
  return {
    checks: [],
    form: {
      data: [{
        menu_id: '',
      },
      ],
    }
  }
},
async created () {
  const response = await api.checkMenuField()
  if (response) {
    this.checks = response.data.data
  }
},

What I knew is code like this, I just learned in a few days ago. Hope you guys can help me to solve the problem.

Thank you

2 Answers

If you use v-model inside v-for you have to send index to each loop to send bind different data to store to your v-model

in template

<v-list-tile v-for="(check,index) in checks" :key="check.menu_id">
 <v-list-tile-content>
  <v-checkbox
   :key="check.menu_id"
   v-model="isChecked[index]"
   :label="check.name"
  >
  </v-checkbox>
 </v-list-tile-content>
</v-list-tile>

in script tag

data: function () {
  return {
    isChecked: [],
    checks: [],
    form: {
      data: [{
        menu_id: '',
      },
      ],
    }
  }
},

isChecked will store Boolean (true,false), so if you want to check that all checkbox is checked, just check all array that is true

methods: {
  isAllChecked(){
    return this.isChecked.every(val => val);
  }
}
Related