How to Watch Props Change with Vue Composition API

Have you recently started using Vue JS in your web stack? Or you’ve started learning about the Vue.js Stack. And you can’t seem to find any examples of How to Watch Component Props.

In this article, you will learn about the methods that you can use to see the props change with Vue composition API.

Watch Props Change With Vue Composition Api

Here, it’s clear that the first argument of a watch can be an array, function, or Ref<T>.

It is a reactive object, and each of its properties is a getter. Props that are passed to a setup function are reactive objects. As a result, what you’re doing is passing the return value of the getter as the first argument of the watch, which is the string “initial,” in this case.

So because the $watch API is used in Vue 2 and the same function is available in Vue 3, you are trying to watch a non-existent property named “initial” on your component.

Only once does your callback get called, and it never gets called again. So at least one time, it is called at least once. The new watch API is behaving just like the current $watch with the immediate option.

watch(() => props.selected, (firstPropToWatch, secondPropToWatch) => {
        "Here Watch props.selected function called with args:",

One function is run right away by Vue to get a list of dependencies (to figure out what should start the callback). The other is called “callback itself.”

Other ways to do this would be to use toRefs to convert the props object so that its properties would be of type Ref<T> and you could pass them as the first argument to the watch.

As each key in the props cannot be reactive always on its own. Hence you may required to adjust the watch function for value having reactive object comparison with ref.

// directly watching a ref that is having reactive object

const selectedProp = ref(props.selected)

watch(selectedProp, (selection, prevSelection) => { 
   /* ... */ 
How to Watch Props Change with Vue Composition API

Wrap Up

I hope you understood how to watch the Props change with Vue composition API. I have listed how two code examples that you can use one is the formal code and another one is the modification of the above to check the props change of reactive objects as well.

Let me know in the comment section if you have a better solution than the one discussed above I will be happy to add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. Remove Duplicate Values From Array – Javascript
  2. How To Reverse A String In Python Using For Loop
  3. Remove Duplicate Values From Array – Javascript
  4. How To Check A Number Is NaN In JavaScript
  5. How To Check A Number Is NaN In JavaScript
  6. Code Example: PopCat Click Hack Code
  7. Best Way To Validate Email Address In JavaScript Regex
  8. How To Create A Dictionary In Python

Leave a Comment