VueJS 代码 - 错误行为 - 怎么了?

VueJS code - wrong behavor - whats wrong?

我在 VueJs 中有这段代码,简单的任务列表,完成的和未完成的,当我选中或取消选中该框时,任务应该移动到正确的列表。

var app = new Vue({
  el: '#vueapp',
  data: {
    tasks: [{
        id: 1,
        description: 'Do some Stuff',
        completed: false
      },
      {
        id: 2,
        description: 'Go to pharmacy',
        completed: false
      },
      {
        id: 3,
        description: 'Go to doctor',
        completed: true
      },
      {
        id: 4,
        description: 'Do some Slask',
        completed: false
      },
    ]
  },
  methods: {
    toggleTask(key) {
      this.tasks[key].completed = !this.tasks[key].completed;
    }
  },
  computed: {
    incompleteTasks() {
      return this.tasks.filter(task => !task.completed);
    },
    completedTasks() {
      return this.tasks.filter(task => task.completed);
    },
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="vueapp">
  <h2>Completed Tasks</h2>
  <ul>
    <li v-for="(task, key) in completedTasks">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
  </ul>

  <h2>Incomplete Tasks</h2>
  <ul>
    <li v-for="(task, key) in incompleteTasks">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
  </ul>
</div>

在 Chrome 中测试。尝试检查第一个未完成的任务,它成功移动到上层列表,但下一个未完成的任务也被检查。!!!!

您需要在循环 :key="task.id" 中添加一个 key

To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item. An ideal value for key would be the unique id of each item.

var app = new Vue({
  el: '#vueapp',
  data: {
    tasks: [{
        id: 1,
        description: 'Do some Stuff',
        completed: false
      },
      {
        id: 2,
        description: 'Go to pharmacy',
        completed: false
      },
      {
        id: 3,
        description: 'Go to doctor',
        completed: true
      },
      {
        id: 4,
        description: 'Do some Slask',
        completed: false
      },
    ]
  },
  methods: {
    toggleTask(key) {
      this.tasks[key].completed = !this.tasks[key].completed;
    }
  },
  computed: {
    incompleteTasks() {
      return this.tasks.filter(task => !task.completed);
    },
    completedTasks() {
      return this.tasks.filter(task => task.completed);
    },
  }
});
.as-console-wrapper { display: none !important; }
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="vueapp">
  <h2>Completed Tasks</h2>
  <ul>
    <li v-for="(task, key) in completedTasks" :key="task.id">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
  </ul>

  <h2>Incomplete Tasks</h2>
  <ul>
    <li v-for="(task, key) in incompleteTasks" :key="task.id">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
  </ul>
</div>