·
1 min read

Vue Tip: Deep Watch on Arrays

Vue Tip: Deep Watch on Arrays Image

In Vue 3, when using the watch option to watch an array, the callback will only trigger when the array is replaced. In other words, the watch callback is not triggered on array mutation.

Let's take a look at an example:

App.vue
<script setup lang="ts"> import { ref, watch } from 'vue' const users = ref([ { id: 1, name: 'Mike' }, { id: 2, name: 'Flo' }, { id: 3, name: 'Chris' }, ]) const addUser = () => { users.value.push({ id: 4, name: 'New' }) } watch(users, (newUsers) => { console.log('New users', newUsers) }) </script> <template> <button @click="addUser">Add user</button> <ul> <li v-for="user of users" :key="user.id"> {{ user.name }} </li> </ul> </template>

We have an array of users and a button to add a new user. When we click the button, the user is added to the array but the watch callback is not triggered.

To trigger the watcher on mutation, the deep option must be specified:

App.vue
<script setup lang="ts"> watch( users, (newUsers) => { console.log('New users', newUsers) }, { deep: true } ) </script>

Now, when we click the button, the watch callback is triggered and the new user is logged to the console.

Try it yourself in the following StackBlitz project:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.