Delete Element in Array Reactively 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.

Let us consider this example -

<template>
  {{ fruits }}
  <v-btn @click="deleteFirst">
    Delete First
  </v-btn>
  <v-btn @click="deleteLast">
    Delete Last
  </v-btn>
</template>
<script>
  export default {
    name: "Farm",
    data() {
      return {
        fruits: ["apple", "orange", "grapes", "pear"]
      };
    },
    methods: {
      deleteFirst() {
        this.fruits.shift();
        // delete last
      },
      deleteLast() {
        this.fruits.pop();
        // delete last
      }
    }
  };
</script>

We just use the standard pop and shift to delete elements in the array. This works just fine and UI is reactive to the changes.

But, you seldom want to remove first/last element in a real-world app. User may want to select a specific fruit or a specific to-do to remove it. We use splice to do exactly that -

<template>
  <template v-for="(fruit, index) in fruits">
    {{ fruit }}
    <v-btn @click="deleteFruit(fruit)">
      Delete Fruit
    </v-btn>
    <br />
  </template>

  <br /><br />
  <v-btn @click="deleteFirst">
    Delete First
  </v-btn>
  <v-btn @click="deleteLast">
    Delete Last
  </v-btn>
</template>
<script>
  export default {
    name: "Farm",
    data() {
      return {
        fruits: ["apple", "orange", "grapes", "pear"]
      };
    },
    methods: {
      deleteFruit(fruit) {
        this.fruits.splice(this.fruits.indexOf(fruit), 1);
        //remove one element starting from the element 'fruit'
      },
      deleteFirst() {
        this.fruits.shift();
        // delete last
      },
      deleteLast() {
        this.fruits.pop();
        // delete last
      }
    }
  };
</script>
Last updated:
Categories: Vue
Tags: VueJS
comments powered by Disqus