Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a row from a table with VueJS

In Vue how do you remove a row from a table when the item is deleted?

Below is how I am rendering the table

<tbody>
  <tr v-for="item in items">
    <td v-text="item.name"></td>
    <td v-text="item.phone_number"></td>
    <td v-text="item.email"></td>
    <td><button @click="fireDelete(item.id)">Delete</button></td>
  </tr>
</tbody>

Below is an excerpt from my Vue component.

data() {
      return {
        items: []
      }
    },

methods: {
    fireDelete(id) {
        axios.delete('/item/'+id).then();
    }
},
mounted() {
      axios.get('/item').then(response => this.items = response.data);
    }

The axios.get work and so does the axios.delete, but the fronend doesn't react so the item is only removed from the table after a page refresh. How do I get it to remove the relevant <tr>?

like image 905
Craig Ward Avatar asked Mar 01 '17 14:03

Craig Ward


People also ask

How do I delete a table row?

Delete a row or column Select a row or column that you want to delete. Press Backspace, or select the Table Tools Layout tab >Delete, and then select an option. Note: In Excel, select a row or column that you want to delete, right-click and select Delete , and choose the option you want.

How do I delete a row in a DataSet?

When using a DataSet or DataTable in conjunction with a DataAdapter and a relational data source, use the Delete method of the DataRow to remove the row. The Delete method marks the row as Deleted in the DataSet or DataTable but does not remove it.

How do I remove a component from Vue?

To make a component delete itself in Vue. js, we can use the this. $destroy method. to add the close method to call this.

How do I remove an item from an array in Vue?

Deleting elements in an array maintains reactivity in Vue when done right. These arrays can be local variables in a component, or state variables in Vuex - the behaviour is the same. We just use the standard pop and shift to delete elements in the array.


2 Answers

I've managed to work out a nice way. I pass the index to the fireDelete method and use the splice function. Works exactly how I wanted.

<tbody>
  <tr v-for="(item, index) in items" v-bind:index="index">
    <td v-text="item.name"></td>
    <td v-text="item.phone_number"></td>
    <td v-text="item.email"></td>
    <td><button @click="fireDelete(item.id, index)">Delete</button></td>
  </tr>
</tbody>


fireDelete(id, index) {
        axios.delete('/item/'+id).then(response => this.organisations.splice(index, 1));
      }
like image 55
Craig Ward Avatar answered Oct 21 '22 17:10

Craig Ward


I had the same trouble as this question. So maybe someone will find this usefull.

For the button use:

v-if="items.length > 1" v-on:click="fireDelete(index)"

And the fireDelete function:

fireDelete: function (index) { 
    this.photos.splice(index, 1);
}
like image 43
Daria Shvydka Avatar answered Oct 21 '22 19:10

Daria Shvydka