Setting a checkbox as checked with Vue.js

前端 未结 5 1942
清歌不尽
清歌不尽 2020-12-13 09:21

I have been googling and playing with every combination I know but I cannot get my checkboxes to be initialised as checked.

Example:

相关标签:
5条回答
  • 2020-12-13 10:09

    In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

    <input
      type="checkbox"
      v-model="toggle"
      true-value="yes"
      false-value="no"
    >
    
    0 讨论(0)
  • 2020-12-13 10:11

    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 each module has a checked property.

    The following code will bind the checkbox with that property:

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

    Notice that I removed v-bind:value="module.id". You shouldn't use v-model and v-bind:value on the same element. From the vue docs:

    <input v-model="something">
    

    is just syntactic sugar for:

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

    So, by using v-model and v-bind:value, you actually end up having v-bind:value twice, which could lead to undefined behavior.

    0 讨论(0)
  • 2020-12-13 10:11

    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:

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

    That should work and the checkbox will display the checkbox with it's current boolean state (if true checked, if not unchecked).

    0 讨论(0)
  • 2020-12-13 10:16

    I use both hidden and checkbox type input to ensure either 0 or 1 submitted to the form. Make sure the field name are the same so only one input will be sent to the server.

    <input type="hidden" :name="fieldName" value="0">
    <input type="checkbox" :name="fieldName" value="1" :checked="checked">
    
    0 讨论(0)
  • 2020-12-13 10:20

    I had similar requirements but I didn't want to use v-model to have the state in the parent component. Then I got this to work:

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

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

    <input
      type="checkbox"
      :checked="aPropFrom"
      @input="$emit('update:aPropFrom', $event.target.checked)"
    />
    
    0 讨论(0)
提交回复
热议问题