How to listen for 'props' changes

Amio.io picture Amio.io · Jun 16, 2017 · Viewed 252.5k times · Source

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.

Answer

Egor Stambakio picture Egor Stambakio · Jun 16, 2017

You can watch props to execute some code upon props changes:

new Vue({
  el: '#app',
  data: {
    text: 'Hello'
  },
  components: {
    'child' : {
      template: `<p>{{ myprop }}</p>`,
      props: ['myprop'],
      watch: { 
      	myprop: function(newVal, oldVal) { // watch it
          console.log('Prop changed: ', newVal, ' | was: ', oldVal)
        }
      }
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <child :myprop="text"></child>
  <button @click="text = 'Another text'">Change text</button>
</div>