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>

1 Answer 1

12

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>

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@ronaldtgi Perhaps you are confusing the checked property (which is a boolean) 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 anyway
Good reference for this prop vs. attr thing: stackoverflow.com/a/6004028/1850609
Uh, my bad, of course it's boolean, it was typo error in my project. Thank you for clarifying it for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.