Learn how to track changes in props in Vue 3 using watchers or lifecycle hooks to respond reactively when parent data updates.
Scalable, Secure, and High-Performance Solutions for Your Business.
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.
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.
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.
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
To listen for prop changes in Vue:
eSparkBiz is rated 4.9 Stars
Real People, Real Stories
See why 300+ startups & enterprises trust eSparkBiz with their software outsourcingIn Vue 2, you need to explicitly install plugins using Vue.use() to add to Vue’s capabilities. This method installs the plugin globally so all components…
In Vue 3, the best way to define global variables is by adding them to app.config.globalProperties during app setup. This makes them accessible across the…
In Vue 3's Composition API, watching for prop changes is essential when you need to respond to updated values passed from a parent component. Unlike…
Let’s discuss how our dedicated experts can help.