function to remove item(any list) does not work in Vuejs

Asked

Viewed 198 times

2

The last method of index.js is removeTodo() that I put a directive on the button but it doesn’t work. thanks! index.html

new Vue({
  el: '#app',
  data(){
    return{
      newTodo:'',
      idforTodo:3,
      todos:[
        {
          id:1,
          title:"escrever um livro",
          completed:false
        },
        {
          id:2,
          title:"Ler sobre Wordpress",
          completed:false
        }
      ]
    }
  },
  methods:{
    addTodo(){
      this.todos.push({
        id: this.idforTodo,
        title: this.newTodo,
        completed:false
      })
      this.newTodo="",
      this.idforTodo++
    },
    removeTodo(index){
      this.todos.slice(index,1)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
  <h2> Todo List</h2>
  <input type="text" v-model="newTodo" />
  <input type="button" value="todo!" @click="addTodo"/>
  <h2>Lista</h2>
<div class="list" v-for="(todo,index) in todos">
  {{todo.id}} - {{todo.title}}
  <input type="button" value="x"  @click="removeTodo(index)"/>


</div>
</div>

  • Try splice instead of Lice

1 answer

1

For this just change the method Slice by the method splice. The Slice method generates another array, exactly with the result of the cuts, that is, it would return the resultados excluídos da lista.

new Vue({
  el: '#app',
  data(){
    return{
      newTodo:'',
      idforTodo:3,
      todos:[
        {
          id:1,
          title:"escrever um livro",
          completed:false
        },
        {
          id:2,
          title:"Ler sobre Wordpress",
          completed:false
        }
      ]
    }
  },
  methods:{
    addTodo(){
      this.todos.push({
        id: this.idforTodo,
        title: this.newTodo,
        completed:false
      })
      this.newTodo="",
      this.idforTodo++
    },
    removeTodo(index){
      this.todos.splice(index,1)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
  <h2> Todo List</h2>
  <input type="text" v-model="newTodo" />
  <input type="button" value="todo!" @click="addTodo"/>
  <h2>Lista</h2>
<div class="list" v-for="(todo,index) in todos">
  {{todo.id}} - {{todo.title}}
  <input type="button" value="x"  @click="removeTodo(index)"/>


</div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.