[Vuejs]-Vue.js remove object from list with two-way binding

0👍

Do not use array indexes to identify elements (keys) in Vue, because with some operations this numbering refreshes. After removing an element from the center of the array, the elements after this position receive a new index value. After removing an element from a 5-element array, with indexes from 0 to 4, you get a 4-element array with indexes from 0 to 3. Vue sees this change as deleting key 4 (last row). Create your own indexes when adding data inside this data.

Vue.component("table-component", {
  template: "#table-template",
  data() {
    return {
      rows: [
        { id: 1, name: "A" },
        { id: 2, name: "B" },
        { id: 3, name: "C" },
        { id: 4, name: "D" },
        { id: 5, name: "E" }
      ]
    };
  },
  methods: {
    removeRow(id) {
      this.rows = this.rows.filter(row => row.id !== id);
    }
  }
});

Vue.component("row-component", {
  template: "#row-template",
  props: ["value"]
});

new Vue().$mount("#app");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table-component :rows="rows" />
</div>

<script type="text/x-template" id="table-template">
  <table v-if="rows.length" border="1" cellpadding="3" cellspacing="3">
    <tbody>
      <row-component v-for="(row, idx) in rows" :key="row.id" v-model="rows[idx]" @removeRow="removeRow"></row-component>
    </tbody>
  </table>
</script>
<script type="text/x-template" id="row-template">
  <tr>
    <td>{{value.id}}</td>
    <td>{{value.name}}</td>
    <td><button @click="$emit('removeRow', value.id)">X</button></td>
  </tr>
</script>

Leave a comment