javascript / intermediate
Snippet
Deep Watching Reactive Objects
When watching nested objects, you need the 'deep' option to track changes inside the object structure. The 'immediate' option triggers the callback once immediately after initialization.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { watch, reactive } from 'vue';const state = reactive({ user: { settings: { theme: 'dark' } } });watch(() => state.user,(newVal) => {console.log('User settings changed!', newVal);},{ deep: true, immediate: true });
vue
Breakdown
1
() => state.user
A getter function that tells the watcher exactly which piece of state to observe.
2
{ deep: true }
Enables recursive observation of all nested properties.
3
immediate: true
Runs the watcher callback instantly with the current value.