How to use watchers in Vue
Watchers in Vue provide a way to perform side effects in response to data changes, enabling reactive programming patterns for API calls, validation, and complex state management.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented watchers in numerous Vue components for form validation, search functionality, and real-time data synchronization in enterprise applications.
From my expertise, the most effective approach is to use the watch option with proper configuration for deep watching and immediate execution.
This method provides precise control over reactive behavior while maintaining clean separation between data and side effects.
Use watch option to observe data properties and execute functions when values change.
<script setup>
import { ref, reactive, watch } from 'vue'
const searchQuery = ref('')
const user = reactive({ name: '', email: '' })
const results = ref([])
// Simple watcher
watch(searchQuery, (newQuery, oldQuery) => {
if (newQuery.length > 2) {
searchUsers(newQuery)
}
})
// Deep watcher with immediate option
watch(user, (newUser) => {
validateUser(newUser)
}, { deep: true, immediate: true })
// Define the methods that are being called
const searchUsers = (query) => {
// Search implementation
console.log('Searching for:', query)
}
const validateUser = (userData) => {
// Validation implementation
console.log('Validating user:', userData)
}
</script>
Watchers observe reactive data properties and execute functions when values change. Simple watchers use property names as keys with functions as values. For complex watching, use object syntax with handler function, deep: true for nested object changes, and immediate: true to run the handler immediately with the current value. Watchers receive the new value and old value as parameters, enabling comparison logic and conditional side effects.
Best Practice Note:
This is the same approach we use in CoreUI Vue components for form validation and data synchronization.
In Vue 3 Composition API, use watch() and watchEffect() functions: watch(() => searchQuery.value, (newQuery) => { /* side effect */ }) for more flexible and composable reactive programming patterns.



