Vuejs strange behavior when a list of checkboxes are updated

128 views Asked by At

Well, it's not easy to explain.

I have a list of checkboxes generated from reactive data. When you check one of the checkboxes, one of the entries of the reactive data is deleted.

The list is then updated.

The next checkbox is then placed under the mouse cursor and is "activated" by releasing the mouse button. This behavior is unwanted, can you see a way to avoid this?

Here is the code to illustrate this case:

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

Script part:

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript" },
      { text: "Learn Vue" },
      { text: "Play around in JSFiddle" },
      { text: "Build something awesome" }
    ]
  },
  methods: {
    toggle: function(){
        this.todos.splice(1,1)
    }
  }
})

Also a live test: https://jsfiddle.net/m10jyLut/7/

I don't know if my design is correct. I would like to avoid a too hackneyed solution.

Thank you very much for your guess.

1

There are 1 answers

3
Bulent On BEST ANSWER

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.