I have been googling and playing with every combination I know but I cannot get my checkboxes to be initialised as checked.
Example:
<ul class="object administrator-checkbox-list">
<li v-for="module in modules">
<label v-bind:for="module.id">
<input type="checkbox" v-model="form.modules" v-bind:value="module.id" v-bind:id="module.id">
<span>@{{ module.name }}</span>
</label>
</li>
</ul>
An example of the modules data:
[
{
"id": 1,
"name": "Business",
"checked": true
},
{
"id": 2,
"name": "Business 2",
"checked": false
},
]
What can I do to initially set the checked status of the checkboxes?
Let's say you want to pass a prop to a child component and that prop is a boolean that will determine if the checkbox is checked or not, then you have to pass the boolean value to the
v-bind:checked="booleanValue"
or the shorter way:checked="booleanValue"
, for example:That should work and the checkbox will display the checkbox with it's current boolean state (if true checked, if not unchecked).
To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over
modules
and eachmodule
has achecked
property.The following code will bind the checkbox with that property:
Notice that I removed
v-bind:value="module.id"
. You shouldn't usev-model
andv-bind:value
on the same element. From the vue docs:So, by using
v-model
andv-bind:value
, you actually end up havingv-bind:value
twice, which could lead to undefined behavior.