Reputation: 7076
My vue component like this :
<template>
...
<ul class="list-unstyled">
<li v-for="category in categories">
...
<input type="checkbox" :value="category.id" :checked="category.id in_array(categoryCountry)">
...
</li>
</ul>
...
</template>
<script>
export default {
props: ['categoryCountry', 'categories'],
}
</script>
I want to change condition in the input
categoryCountry is array, for example array(1,2,3)
So if category.id in array of categoryCountry, then it will checked
How can I do it?
Upvotes: 0
Views: 2675
Reputation: 2993
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)">
Upvotes: 2
Reputation: 2340
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.
Upvotes: 0
Reputation: 506
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
Upvotes: 0