How to listen for 'props' changes

ghz 8months ago ⋅ 143 views

In the VueJs 2.0 docs I can't find any hooks that would listen on props changes.

Does VueJs have such hooks like onPropsUpdated() or similar?

Update

As @wostex suggested, I tried to watch my property but nothing changed. Then I realized that I've got a special case:

<template>
    <child :my-prop="myProp"></child>
</template>

<script>
   export default {
      props: ['myProp']
   }
</script>

I am passing myProp that the parent component receives to the child component. Then the watch: {myProp: ...} is not working.

Answers

In Vue.js, there isn't a specific hook like onPropsUpdated() to listen directly for changes to props. Instead, you can use watchers or computed properties to achieve similar functionality.

  1. Watchers: You can watch for changes to specific props using watchers. Watchers allow you to perform side effects or actions when the value of a prop changes.

    export default {
      props: ['myProp'],
      watch: {
        myProp(newValue, oldValue) {
          // Perform actions when myProp changes
          console.log('myProp changed:', newValue);
        }
      }
    }
    
  2. Computed Properties: Computed properties can also indirectly listen for changes to props by depending on them. Whenever the value of a prop changes, computed properties that depend on that prop will be re-evaluated.

    export default {
      props: ['myProp'],
      computed: {
        computedProp() {
          // Depend on myProp
          return this.myProp * 2; // For example
        }
      }
    }
    

In your specific case, where you're passing myProp from the parent component to the child component, you can use watchers or computed properties in the child component to react to changes in myProp.

If you're using a watcher in the child component and it's not working as expected, double-check that the prop name matches exactly (case-sensitive) and that the value is being passed correctly from the parent component. If you're still facing issues, there might be other factors at play, such as asynchronous updates or component lifecycle timing.