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 Vue 2, you no longer use watch: {} in the options API but instead use the watch() function with toRefs() or toRef().
How to Watch Props in Vue 3 Composition API
To reactively watch a prop, use the watch() function inside the setup() method. Vue requires props to be wrapped with toRef() or toRefs() to retain reactivity.
Using toRef()
<script setup>import { watch, toRef } from ‘vue’
defineProps([‘someProp’])
const props = defineProps()
const someProp = toRef(props, ‘someProp’)
watch(someProp, (newVal, oldVal) => {
console.log(‘Prop changed:’, oldVal, ‘→’, newVal)
})
</script>
Using toRefs()
<script setup>import { watch, toRefs } from ‘vue’
const props = defineProps()
const { someProp } = toRefs(props)
watch(someProp, (newVal, oldVal) => {
console.log(‘Updated:’, newVal)
})
</script>
Also Read: The Top Websites Built with Vue JS
Common Gotchas
Destructuring props without toRefs() or toRef() breaks Vue’s reactivity system. Use toRefs(props) for multiple props or toRef(props, ‘key’) for a single prop to keep reactivity intact.
Key Takeaway
In Vue 3 Composition API, use watch() with toRef() or toRefs() to track prop changes reactively. This helps you respond to parent-driven updates within components.