DEV Community

Cover image for Watch props in Vue
Graham Morby
Graham Morby

Posted on

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