Problem in creating list in Vue.js

2

This is part of the HTML code in question:

<div class="row">
        <h1>Minha lista de elementos</h1>
        <input type="text" class="form-control" v-model="newElement" v-on:keyup.enter="addElement">
        <ul>
            <li v-for="element in elements">
                {{ element.title }}
                <a href="#" v-on:click="removeElement($event,$index)">X</a>
            </li>

        </ul>
    </div>

My Javascript code

var hello = new Vue({
    el:'#hello',
    data:{
                msg: "Hello pessoal",
                peoples:[
                    {name: "Maria"},
                    {name: "Gustavo"},
                    {name: "Ricardo"},
                    {name: "Wladimir"}
                ],
                newElement:'',
                elements:[]
            },
            methods:{
                addElement: function(){
                /*  console.log(e); */
                var title = this.newElement.trim();
                    if(title){
                        this.elements.push({title:title});
                        this.newElement = "";   
                    } 
                },
                removeElement: function(e,index){
                    e.preventDefault();
                    this.elements.splice(index,1);
                }
        }
});

What happens is that it's deleting items added, but it's not deleting in order, could you please take a look, I believe it's bullshit.

    
asked by anonymous 19.09.2017 / 20:37

2 answers

3

You need to pass the index to this function, e.preventDefault() does not need to be in the function, you can do with v-on:click.prevent .

A suggestion of code might look like this:

<li v-for="(element, i) in elements">
   {{ element.title }}
   <a href="#" v-on:click.prevent="removeElement(i)">X</a>
</li>

then:

removeElement: function(index){
    this.elements = this.elements.filter((el, i) => i != index);
}
    
19.09.2017 / 20:52
4

In the for loop you must specify that you are going to have access to the corresponding index, try this:

<li v-for="(element, index) in elements">
    {{ element.title }}
    <a href="#" v-on:click="removeElement($event,index)">X</a>
</li>

DOCS

    
19.09.2017 / 20:46