This page looks best with JavaScript enabled

Delete Element in Array Reactively in Vue

 ·   ·  ☕ 2 min read

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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<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>
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things