Skip to content

Set checkbox selected in Vue

I am beginner in vue and web developing. I make my app with Laravel and Vue.

I have this code:

created: function () {
let self = this;
self.setActive('tab1');
axios.get(this.$apiAdress + '/api/tasks/create?token=' + localStorage.getItem("api_token"))
.then(function (response) {
self.documentDircionary = response.data.documentDircionary;
self.selectedDocumentDircionary = response.data.selectedDocumentDircionary;
}).catch(function (error) {
console.log(error);
self.$router.push({path: '/login'});
});
<template v-for="(option) in documentDircionary">
   <div class="form-group form-row" :key="option.name">
      <CCol sm="12">
         <input type="checkbox" name="selectedDocuments[]" :id="option.value" /> {{ option.label }}
      </CCol>
   </div>
</template>

This code show me inputs – and it’s work fine. I have problem with set selected attribute for selected checkbox.

In array selectedDocumentDircionary results from api:

"selectedProducts": [1,2,43]

How can I set checked for only this checkbox, witch selectedProducts?

Please help me

Answer

You can set :checked based on if the id of the current element is in the array:

<template v-for="(option) in documentDircionary">
   <div class="form-group form-row" :key="option.name">
      <CCol sm="12">
         <input type="checkbox" name="selectedDocuments[]" :id="option.value" :checked="selectedProducts.includes(option.value)" /> {{ option.label }}
      </CCol>
   </div>
</template>