JAVASCRIPT

Vue 3 Advanced watch with Options

Master Vue 3's `watch` function by demonstrating deep observation, immediate execution, and various flush timings for precise reactivity control.

import { ref, watch, reactive, onMounted } from 'vue';

// A reactive object to demonstrate deep watching
const userProfile = reactive({
  name: 'Jane Doe',
  settings: {
    theme: 'dark',
    notifications: true,
  },
  preferences: ['email', 'sms'],
});

// A simple ref to demonstrate basic watching with immediate execution
const message = ref('Initial message');

// A ref for a counter to show different flush timings
const counter = ref(0);

// 1. Deep watch an object's nested properties
watch(userProfile, (newProfile, oldProfile) => {
  console.log('User profile changed deeply:', newProfile, oldProfile);
  // This will trigger even if userProfile.settings.theme changes or preferences array mutates
}, { deep: true });

// 2. Watch with immediate execution (runs once on setup, then on changes)
watch(message, (newMessage, oldMessage) => {
  console.log('Message updated (immediate):', newMessage, oldMessage);
}, { immediate: true });

// 3. Watch with 'pre' flush timing (runs before component renders)
watch(counter, (newVal, oldVal) => {
  console.log('Counter changed (flush: "pre"):', newVal, oldVal);
  // Perform actions that should happen before the DOM updates
}, { flush: 'pre' });

// 4. Watch with 'post' flush timing (runs after component renders - default)
watch(counter, (newVal, oldVal) => {
  console.log('Counter changed (flush: "post"):', newVal, oldVal);
  // Access updated DOM elements here (e.g., this.$refs.myElement.textContent will be updated)
}, { flush: 'post' }); // 'post' is the default and can be omitted

// Simulate changes (typically these would be user interactions or data fetches)
onMounted(() => {
  console.log('Component mounted. Simulating changes...');

  setTimeout(() => {
    message.value = 'Hello Vue!';
  }, 500);

  setTimeout(() => {
    userProfile.settings.theme = 'light'; // Triggers deep watch
  }, 1000);

  setTimeout(() => {
    userProfile.preferences.push('push'); // Triggers deep watch due to array mutation
  }, 1500);

  setTimeout(() => {
    counter.value++; // Triggers counter watches
  }, 2000);

  setTimeout(() => {
    counter.value++; // Triggers counter watches again
  }, 2500);
});

// This snippet is typically used within a <script setup> block or a composable.
// To illustrate, if used in a regular setup function:
// export default {
//   setup() {
//     // all the watch calls and reactive variables would be defined here
//     return { userProfile, message, counter };
//   }
// }
How it works: This snippet demonstrates the powerful `watch` function in Vue 3's Composition API, showcasing its advanced options. It covers `deep: true` for observing changes within nested properties of reactive objects, `immediate: true` to run the watcher callback immediately upon component setup in addition to subsequent changes, and different `flush` timings (`pre` and `post`). `flush: 'pre'` executes the watcher before the component's DOM updates, useful for tasks requiring the old DOM state, while `flush: 'post'` (the default) runs after DOM updates, enabling access to the latest DOM. These options provide fine-grained control over reactivity.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs