2

I'm trying to move a checkbox to a child component, but I can't get it to update the data stored in the parent.

Parent:

<template>
  <CheckboxComponent
    :value="profile.doYouAgree"
    label="Do you agree?"
    @input="profile.doYouAgree = $event.target.value"
  />
  <div>{{ profile.doYouAgree }}</div>
</template>

<script>
import CheckboxComponent from "./components/CheckboxComponent.vue";
import { reactive } from "vue";
const profile = reactive({
  name: "A Name",
  email: "[email protected]",
  doYouAgree: false,
});

export default {
  name: "App",
  components: {
    CheckboxComponent,
  },
  setup() {
    return {
      profile,
    };
  },
};
</script>

Child:

<template>
  <div class="hello">
    <label for="checkbox">{{ label }}</label>
    <input
      type="checkbox"
      :value="modelValue"
      right
      @input="$emit('update:modelValue', $event.target.value)"
    />
  </div>
</template>

<script>
export default {
  name: "CheckboxComponent",
  props: {
    label: {
      type: String,
      default: "",
    },
    modelValue: {
      type: Boolean,
    },
  },
};
</script>

In the following sandbox, I am expecting the false to turn to true when the box is checked: https://codesandbox.io/s/gifted-worker-vm9lyt?file=/src/App.vue

1 Answer 1

3

There's a couple of problems here:

  1. $event.target.value is a string rather than a boolean. Change this to $event.target.checked
  2. Your parent is listening to input but your child is emitting update:modelValue. Save yourself a lot of hassle and use v-model in the parent:
<CheckboxComponent
  v-model="profile.doYouAgree"
  label="Do you agree?"
/>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Daniel, that was it, I did notice that the value in my object was changing to a String of "false" instead of the Boolean false and that was due to me using $event.target.input. Thanks!

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.