JAVASCRIPT
Vue 3 Watchers for Reactive Side Effects
Handle asynchronous operations and side effects in Vue 3 using the watch function to track state changes.
import { ref, watch } from 'vue';
export default {
setup() {
const searchQuery = ref('');
watch(searchQuery, async (newValue, oldValue) => {
if (newValue.trim() !== '') {
console.log(`Searching for: ${newValue}`);
// Perform API request here
}
});
return { searchQuery };
}
};
How it works: Vue 3 watch function allows you to execute custom callback logic whenever a specific reactive reference or getter changes. This is ideal for handling side effects like data fetching or analytics tracking.