Blog>
Snippets

Vue 3 Watchers for State Change Detection

Provide an example of how to use Vue 3's watcher functions to react to specific state changes and perform side effects.
<script setup>
import { ref, watch } from 'vue';

// Stateful reference that we want to watch
const count = ref(0);

// Watcher for the count reference
// This will run on every change of the count value
watch(count, (newValue, oldValue) => {
  console.log(`Count changed from ${oldValue} to ${newValue}`);
  // Perform side effects here based on new value of count
});

// Another example with a complex state object
const state = ref({
  firstName: 'John',
  lastName: 'Doe'
});

// Watch specific property of the state object
watch(() => state.value.lastName, (newLastName, oldLastName) => {
  console.log(`Last name changed from ${oldLastName} to ${newLastName}`);
  // Actions based on lastName changes can be performed here
});
</script>
This code snippet defines two Vue 3 refs, 'count' and 'state', with watchers that listen for changes. The first watcher will log to the console whenever 'count' changes, while the second will do the same for the 'lastName' property within the 'state' object. Inside the watcher callbacks, you can perform any actions that should occur as a side effect of the state changes.