nlassaux
nlassaux

Reputation: 2406

Delete an item of a computed list in Vue.js

I would need to display a list of items, and be able to erase one of them when needed.

  <tr v-for="(todo, key, index) in todo_list">
    <td><input v-model.trim="todo.priority" type="number"/></td>
    <td><a v-on:click="todo_list.splice(index, 1)">Delete</a></td>
  </tr>

The problem here is the fact that todo_list is computed. Thanks to the v-model, I can edit the priority. I can notice that edit. But I want to be able to delete any item too. It doesn't trigger any error or warning (vue.js file non-minified).

I tried Vue.delete(todo_list, index), I tried to pass key instead of index, to do it in a method. None of that worked. Note: when I tried the method, I entered in it: I could log in the console before and after the splice.

I can create an attribute in data that would mirror that computed value, but I believe it would be useless code. Is there a way to to achieve that?

Upvotes: 1

Views: 3333

Answers (1)

CodinCat
CodinCat

Reputation: 15914

If each todo has a unique key, just use these key to delete from original data.

a todo:

{
  key: 0,
  priority: 5,
  ...
}

Example: http://codepen.io/CodinCat/pen/LxjLoE?editors=1010

v-on:click="() => remove(todo.key)"

and the remove method:

remove (key) {
    this.todoList = this.todoList.filter(todo => todo.key !== key)
}

Upvotes: 2

Related Questions