Vue Tip: Deep Watch on Arrays
Michael Hoffmann
@mokkapps
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:
<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:
<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 BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
Nuxt Tip: Custom SPA Loading Template for Your Nuxt Application
Nuxt Tip: An URL Object Working on Both Server-Side and Client-Side