DEV Community

Cover image for Watch props in Vue
Graham Morby
Graham Morby

Posted on

5

Watch props in Vue

I had a wonderful night helping a fellow developer last night and thought I'd share something even I had to look up again.

Watching props in Vue 2 is pretty simple and mostly the same as watching any data point.

So if we set up a vue component with a prop declared:

<template>
    <h1>{{propData}}</h1>
</template>

<script>
export default {
     el: '#app',
     data: {
        text: 'Hello'
     },
     props: ['propData'],
   }
</script>
Enter fullscreen mode Exit fullscreen mode

So to simply watch the prop for changes we do as follows:

watch: {
        propData: function () {
            deep: true,
            handler(newValue, oldValue) {
                console.log(newValue);
            }
        } 
    }
Enter fullscreen mode Exit fullscreen mode

So the Deep part of the set up is if we were watching an Object or an Array which would allow the watch to look into the data structure and check for changes.

Top comments (1)

Collapse
 
vkyrychenko profile image
Vitalii

Strange construction. Does it work for you?

I guess propData should be an object instead of function:

{
  watch: {
    propData: {
      deep: true,
      handler(newValue, oldValue) {
        console.log(newValue);
    }
  } 
}
Enter fullscreen mode Exit fullscreen mode

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay