Set the checkbox checked by Vue.js

I play games and play with every combination I know, but I canโ€™t check my checkboxes as noted.

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 these modules:

 [ { "id": 1, "name": "Business", "checked": true }, { "id": 2, "name": "Business 2", "checked": false }, ] 

What can I do to initially set checked flag states?

+21
javascript
source share
3 answers

To set the checkbox value, you need to bind the v-model to the value. The checkbox will be checked if the value is true. In this case, you iterate through the modules , and each module has a checked property.

The following code will associate the checkbox with this property:

 <input type="checkbox" v-model="module.checked" v-bind:id="module.id"> 

Please note that I removed v-bind:value="module.id" . You should not use v-model and v-bind:value for the same element. From vue docs :

 <input v-model="something"> 

is just syntactic sugar for:

 <input v-bind:value="something" v-on:input="something = $event.target.value"> 

So, using v-model and v-bind:value , you actually get v-bind:value twice, which can lead to undefined behavior.

+33
source share

Suppose you want to pass a support to a child component and that prop is a boolean that will determine whether the checkbox is checked or not, then you must pass the boolean to v-bind:checked="booleanValue" or a shorter path :checked="booleanValue" , for example:

 <input id="checkbox" type="checkbox" :value="checkboxVal" :checked="booleanValue" v-on:input="checkboxVal = $event.target.value" /> 

This should work, and the checkbox will display the checkbox with its current logical state (if true, if not checked).

+14
source share

I had requirements for a smiler, but I did not want to use v-model to have state in the parent component. Then I will make it work.

 <input type="checkbox" :checked="checked" @input="checked = $event.target.checked" /> 

To pass the value from the parent, I made a small change to it, and it works.

 <input type="checkbox" :checked="aPropFrom" @input="$emit('update:aPropFrom', $event.target.checked)" /> 
+1
source share

All Articles