Sometimes, we want to watch props change with Vue Composition API and Vue 3.
In this article, we’ll look at how to watch props change with Vue Composition API and Vue 3.
How to watch props change with Vue Composition API and Vue 3?
To watch props change with Vue Composition API and Vue 3, we can use the watch
function.
For instance, we write
watch(() => props.selected, (selection, prevSelection) => {
/* ... */
})
to call watch
to watch the selected
prop.
We get the latest and previous value of it from the parameters in the 3rd argument.
Also, we can also put the prop in a ref and watch the ref with
const selected = ref(props.selected);
watch(selected, (selection, prevSelection) => {
/* ... */
});
And we can watch multiple refs with
watch([ref1, ref2], ([refVal1, refVal2], [prevRef1, prevRef2]) => {
/* ... */
});
Conclusion
To watch props change with Vue Composition API and Vue 3, we can use the watch
function.
3 replies on “How to watch props change with Vue Composition API and Vue 3?”
Simply and effective. Thanks
Awesome, thanks so much
wrapping prop in ref() doesn’t cause the watch handler to get fired, so it doesn’t work as you’ve described here.
(see WrapRef.vue section here https://stackblitz.com/edit/nuxt-starter-ydulh2?file=components/WrapReactive.vue)