Javascript is required
·
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
1<script setup lang="ts">
2import { ref, watch } from 'vue'
3
4const users = ref([
5  { id: 1, name: 'Mike' },
6  { id: 2, name: 'Flo' },
7  { id: 3, name: 'Chris' },
8])
9
10const addUser = () => {
11  users.value.push({ id: 4, name: 'New' })
12}
13
14watch(users, (newUsers) => {
15  console.log('New users', newUsers)
16})
17</script>
18
19<template>
20  <button @click="addUser">Add user</button>
21  <ul>
22    <li v-for="user of users" :key="user.id">
23      {{ user.name }}
24    </li>
25  </ul>
26</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
1<script setup lang="ts">
2watch(
3  users,
4  (newUsers) => {
5    console.log('New users', newUsers)
6  },
7  { deep: true }
8)
9</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.