List creation problem in Vue.js

Asked

Viewed 43 times

2

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 is deleting the added items, however it is not deleting in the order, could take a look please, I believe it is bullshit.

2 answers

4

In the for cycle you must specify that you are traversing in order to have access to the corresponding Dice, try this:

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

DOCS

  • sorry, but it is still not working, when I click on X to remove, it is removing randomly.

  • It’s removing from top to bottom regardless of which I click.

3


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

A suggested code could be like this:

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

and then:

removeElement: function(index){
    this.elements = this.elements.filter((el, i) => i != index);
}
  • 1

    thanks, thanks, it worked.

  • Sergio sorry, can you explain why in my case it doesn’t work sff, the preventDefault() don’t do what you expect? I could swear it would work. Tomorrow I delete the answer, now I can’t because I’m in the app

  • @Miguel no :) Your code is valid and works https://jsfiddle.net/Sergio_fiddle/ey349pot/

  • @Sergio is always obsessed by the example, but do you have any idea why the AP said he wasn’t?

  • 1

    @Not Miguel. I suggest you ask.

Browser other questions tagged

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