Blog>
Snippets

Reactive Arrays and their Caveats

Showcase common operations on reactive arrays and discuss the caveats and workarounds in Vue.js 3.
<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">{{ item }}</li>
    </ul>
    <button @click="addItemToEnd">Add Item to End</button>
    <button @click="updateFirstItem">Update First Item</button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const items = ref(['apple', 'banana', 'cherry']);

    function addItemToEnd() {
      // Vue 3 reactivity system tracks array mutations so this will be reactive
      items.value.push('date');
    }

    function updateFirstItem() {
      // Caveat: Vue cannot detect when an array item is directly set by index
      // However, since Vue 3 uses Proxy, this is now reactive without workarounds
      items.value[0] = 'avocado';
    }

    return { items, addItemToEnd, updateFirstItem };
  }
};
</script>

<style>
ul {
  list-style-type: none;
  padding: 0;
}
li {
  margin: 5px 0;
}
</style>
HTML template with a Vue 3 component script that demonstrates reactivity with arrays. The setup() function uses the ref() to create a reactive array. It showcases adding an element to the end of the array and updating the first element directly by index. Vue 3's reactivity system now handles both cases without caveats.
<script>
import { ref } from 'vue';

export default {
  setup() {
    const items = ref(['apple', 'banana', 'cherry']);

    function removeFirstItem() {
      // Reactive way to remove an item by using array methods
      items.value.shift();
    }

    function removeItemAtIndex(index) {
      // To remove an item at specific index,
      // splice method should be used to maintain reactivity
      items.value.splice(index, 1);
    }

    return { items, removeFirstItem, removeItemAtIndex };
  }
};
</script>
An example showing how to remove items from a reactive array using array methods like shift() and splice() in Vue 3 setup function. The reactivity system keeps track of these changes, making it easy to reflect updates in the component's template.