lundi 19 décembre 2022

Vue3: Controlling checkbox checked state by a component prop

This is the setup:

Parent component: Has a reactive Todo object with a checked state {checked: true and passes it to a Todo component.

Todo component: Accepts the Todo as a prop and binds the checked value to a checkbox. Upon toggling the checkbox, it emits an event to the parent, which then asynchronously updates the checked state of the Todo.

Parent:

<template>
  <Todo @update="handleUpdate" :todo="todo" />
</template>

<script setup>
import { reactive } from "vue";
import Todo from "./components/Todo.vue";

let todo = reactive({ checked: true });

let handleUpdate = (e) => {
  setTimeout(() => {
    // Always sets it to false for test purposes
    todo.checked = false;
  }, 1000);
};
</script>

Child:

<template>
  <input type="checkbox" v-model="checkboxProxy" />
</template>

<script setup>
const { computed, defineProps, defineEmits } = require("vue");

let props = defineProps(["todo"]);
let emit = defineEmits(["update"]);

let checkboxProxy = computed({
  get() {
    return props.todo.checked;
  },
  set(val) {
    emit("update", val);
  },
});
</script>

Question: I would expect the checkbox to get unchecked a second after it has been checked. But that doesn't happen. Why?

Codesandbox: https://codesandbox.io/s/crazy-snow-kdse27

I also tried this setup:

<input type="checkbox" :checked="todo.checked" @change="emit('update)" />

But it still not reflecting the todo state. I'm testing in Brave it that matters.




Aucun commentaire:

Enregistrer un commentaire