Why You Need to Watch Props in Vue
In Vue.js, props allow a parent component to pass data to a child. Sometimes, you need to perform actions when a prop value changes, like fetching new data or re-rendering part of the UI.
Vue doesn't automatically react to prop changes with side effects, so you must manually watch them.
Method 1: Using watch() in Vue 3 (Composition API)
Inside the setup() function, use watch() to react to specific prop changes.
import { watch, defineComponent } from 'vue';
export default defineComponent({
props: {
userId: Number,
},
setup(props) {
watch(() => props.userId, (newVal, oldVal) => {
console.log('User ID changed from', oldVal, 'to', newVal);
// Perform action based on new prop value
});
}
});
Best for: reactive logic using Composition API.
Method 2: Using the watch Option in Options API
Define watchers directly in your component to respond to prop changes in the Options API style.
export default { props: ['userId'],
watch: {
userId(newVal, oldVal) {
console.log(`User ID changed from ${oldVal} to ${newVal}`);
}
}
}
Best for: legacy or Options API-based components.
Alternative: Use updated() Lifecycle Hook
Use this if you need to run code after any reactive update, not just specific prop changes.
export default { props: ['status'],
updated() {
console.log('Component has updated (could be due to prop, data, or state change).');
// This hook runs after the component has been updated in the DOM.
}
}
Not ideal for targeting individual prop changes, better suited for general post-update logic.
Also Read: Best Vue.js Framework Of All Time
Common Mistakes to Avoid
- Assuming Vue will auto-react to all prop changes
- Forgetting to return a function in watch(() => props.myProp) in Composition API
- Using created() or mounted() for watching dynamic changes — these only run once
Summary
To listen for prop changes in Vue:
- Use watch() in the Composition API
- Use the watch option in the Options API
- Avoid lifecycle hooks for precise prop watching
Related Resources