Watch props in Vue
Graham Morby

Graham Morby @grahammorby

About: Hey guys, 15-year developer! I code with Vue.js and Python, I love to learn but also love to teach! So I try and write informative tutorials and posts. I am new to blogging and would love any feedback

Location:
Portsmouth UK
Joined:
Dec 9, 2019

Watch props in Vue

Publish Date: Sep 21 '20
5 1

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.

Comments 1 total

  • Vitalii
    VitaliiNov 24, 2023

    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
Add comment