0

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?

3 Answers 3

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)"> 
Sign up to request clarification or add additional context in comments.

1 Comment

which is exactly what I wrote
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.