mercredi 16 septembre 2020

VueJS - Checkbox "checked" attribute is inconsistent with its state

This is a simple todo-list example, where I'd like the checkboxes to be checked or not, depending on the task being completed or not.

After unchecking a checkbox under the "Complete tasks" section, the next checkbox will appear unchecked, even though it's still checked in the "All tasks" section.

To reproduce easily, uncheck "Go to the store" in the "Complete tasks" section. "Clean room" will appear unchecked, even though it's still checked in "All tasks", and still completed in the data.

How can I fix this ?

<html>
<head>
    <title>VueJS</title>
</head>
<body>
<div id="root">
    <h1>All tasks</h1>

    <ul>
        <li v-for="task in tasks">
            
            <input type="checkbox" v-model="task.completed" :id="task.id">
        </li>
    </ul>

    <h1>Complete tasks</h1>

    <ul>
        <li v-for="completeTask in completeTasks">
            
            <input type="checkbox" v-model="completeTask.completed" :id="completeTask.id">
        </li>
    </ul>

    <h1>Incomplete tasks</h1>

    <ul>
        <li v-for="incompleteTask in incompleteTasks">
            
            <input type="checkbox" v-model="incompleteTask.completed" :id="incompleteTask.id">
        </li>
    </ul>
</div>

<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>

<script>
  new Vue({
    el: '#root',
    data: {
      tasks: [
        {id: 1, description: 'Go to the store', completed: true},

        {id: 2, description: 'Finish X', completed: false},

        {id: 3, description: 'Do Y', completed: false},

        {id: 4, description: 'Clear inbox', completed: false},

        {id: 5, description: 'Make Z', completed: false},

        {id: 6, description: 'Clean room', completed: true},
      ],
    },

    computed: {
      completeTasks() {
        return this.tasks.filter(task => task.completed);
      },

      incompleteTasks() {
        return this.tasks.filter(task => !task.completed);
      },
    },
  });
</script>
</body>
</html>



Aucun commentaire:

Enregistrer un commentaire