[Vuejs]-How can I make in array in vue component?

2👍

The best and simple answer. using “includes” it check if the data exist in array.

example:

[].includes(something);

answer on your codes.

<input type="checkbox" :value="category.id" :checked="categoryCountry.includes(category.id)"> 

0👍

using v-if you can pass a function so, you can make a method in vue that checks your array like

checkInArray: (needle, haystack) {
    return haystack.includes(needle)
}

The on your input

<input v-if="checkInArray(categoryCountry, categories)"

Array.prototype.includes() returns a bool true/false which is enough to satisfy a conditional v-if

0👍

If you receive an array and you need to display each item of the array as an input checkbox you should iterate through each array item:

// Template example
<div id='check_box_sample'>
  <div v-for="category in categoryCountries">
    <input 
      type="checkbox" 
      :id="category"
      :value="category"
      v-model="checkedCategories">
    <label 
      :for="category">
      {{ category }}
    </label>
  </div>
  <br>
  <span>Checked names: {{ checkedCategories }}</span>
</div>

So for each iteration on the v-for="category in categoryCountries" you create an input type checkbox, you have to define an id :id="category" and a value :value="category"since this is only a simple example I just use the same array item.

You may want to see a working example

I hope this help you.

Leave a comment