3

Trying to create a checkbox without using v-model

<input type="checkbox" :value="value" @change="$emit('input', $event.target.checked)" />

The checkbox will check and uncheck, and the input event is sent to the parent, but the value doesn't change. My parent component looks like this:

<custom-component v-model="some_boolean_value"></custom-component>
Dave
  • 2,735
  • 8
  • 40
  • 44

1 Answers1

10

For checkboxes, use :checked instead of :value. See demo below.

Vue.component('custom-component', {
  template: '#custom',
  props: ['value']
})
new Vue({
  el: '#app',
  data: {
    some_boolean_value: true
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>some_boolean_value: {{ some_boolean_value }}</p>
  <custom-component v-model="some_boolean_value"></custom-component>
</div>

<template id="custom">
  <div style="border: 2px dashed red;">
    <input type="checkbox" :checked="value" @change="$emit('input', $event.target.checked)" />
  </div>
</template>
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • Thanks, this was only half of my problem. (The other half with code not in my original question) It looks like value does have some effect, but the initial state of the checkbox is always unchecked, even if you set value to true. – Dave Apr 11 '18 at 14:27
  • @ronaldtgi Perhaps you are confusing the `checked` property ([which is a boolean](https://developer.mozilla.org/docs/Web/API/HTMLInputElement)) with the `checked` attribute, no? The latter can only be a string, but its value doesn't matter at all: if the attribute is declared, even if empty (eg `checked=""`) the checkbox will have its `checked` _property_ set to `true`. At any rate, this difference is only noticeable in vanilla HTML/JS, because when vue sees the `:checked` [it always treats it as a prop](https://github.com/vuejs/vue/blob/v2.6.14/src/platforms/web/util/attrs.js#L11-L18) anyway – acdcjunior Jul 16 '21 at 20:55
  • Good reference for this prop vs. attr thing: https://stackoverflow.com/a/6004028/1850609 – acdcjunior Jul 16 '21 at 20:56
  • Uh, my bad, of course it's boolean, it was typo error in my project. Thank you for clarifying it for me. – ronaldtgi Jul 17 '21 at 02:48