softya
softya

Reputation: 260

vuejs2 splice remove only last element

hi im trying to remove element from array in vuejs2 and this is my html code

<tr class="o_data_row o_selected_row" v-for='(line , id) in lines'>
    <td>anything here</td>
    <td class="o_list_record_remove" style='width:10%'>
        <button @click='remove_line(id)' class="fa fa-trash-o" name="delete"></button>
    </td>
</tr>

and this is my vuejs2 code

remove_line:function(index)
{
    console.log(index);
    console.log(this.lines);
    this.lines.splice(index,1);
}

in console i gat correct index and the lines also is correct .. i dont know whats wrong with the code thanks a lot ..

enter image description here

Upvotes: 1

Views: 121

Answers (2)

Emir Vatric
Emir Vatric

Reputation: 11

<button v-on:click="lines.splice(id, 1)" class="fa fa-trash-o" name="delete"></button>

or

<button @click.prevent='remove_line(id)' class="fa fa-trash-o" name="delete"></button>

Upvotes: 1

Anatoly
Anatoly

Reputation: 22803

  1. use some unique prop for each element in the 'lines' array not an index.
  2. Add this unique prop to :key where v-for is located like this:
<tr class="o_data_row o_selected_row" v-for='(line , id) in lines' :key="line.uniq_prop">
  1. Pass the lines item in the remove_line function like this:
<button @click='remove_line(line)'
  1. In the remove_line find an element's index that is about to delete and splice it:
remove_line:function(line)
{
    console.log(line);
    console.log(this.lines);
    const index = this.lines.indexOf(line);
    this.lines.splice(index,1);
}

Upvotes: 1

Related Questions