[Vuejs]-Vue3: Controlling checkbox checked state by a component prop

1👍

You are not changing the todo object itself but just the HTML element. Meaning, once the state is set to false it is not updated to true when you emit the event.
And because you use reactive and computed the state is cached, so nothing will happen until something is changed.

let handleUpdate = (e) => {
// actually changing the state here
todo.checked = true;
  setTimeout(() => {
    // Always sets it to false for test purposes
    todo.checked = false;
  }, 1000);
};

todo.checked = true is going to change the state and after one second (in your case) it is going to be set back to false, which respectively will update the props and the checkbox itself.

Updated:

To update the checkbox based on the response you can either:

  1. prevent the default action and update if needed (when the response is ready).

Todo.vue

<div>
    <input type="checkbox" :checked="props.todo.checked" @click.prevent="emit('update', $event.target.value)" />
    <div>Prop value: {{ todo }}</div>
  </div>
  1. Update the state before the response, and then set the data from the response if there is a change as in the example from above.

If I’m not mistaken, using Vue.set() in vue 2 actually will result in the same (visual) behavior as pt2

Keep in mind that both ways are not very UX-friendly.

👤Zarko

Leave a comment