[Vuejs]-Vuejs strange behavior when a list of checkboxes are updated

0πŸ‘

βœ…

I added "key" to v-for, which is always a good idea, and passing todo.id with toggle().

<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="todo in todos" :key="todo.id">
      <label>
        <input type="checkbox"
          v-on:change="toggle(todo.id)">
        {{ todo.text }}
      </label>
    </li>
  </ol>
</div>

Your script tag should be like this:

new Vue({
  el: "#app",
  data: {
    todos: [
      { id: Math.random() * 100000, text: "Learn JavaScript",  },
      { id: Math.random() * 100000, text: "Learn Vue", },
      { id: Math.random() * 100000, text: "Play around in JSFiddle", },
      { id: Math.random() * 100000, text: "Build something awesome", }
    ]
  },
  methods: {
    toggle(id) {
        this.todos = this.todos.filter(todo => todo.id !== id)
    }
  }
})

In Vue.js, it’s always a good idea to add key to v-for, and working with ids for rendering operations.

Leave a comment