How to listen for 'props' changes

Javascriptvue.jsVuejs2Vue Component

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

Have you tried this ?

watch: {
  myProp: {
    // the callback will be called immediately after the start of the observation
    immediate: true, 
    handler (val, oldVal) {
      // do your stuff
    }
  }
}

https://vuejs.org/v2/api/#watch

Solution 3 - Javascript

In my case I needed a solution where anytime any props would change, I needed to parse my data again. I was tired of making separated watcher for all my props, so I used this:

  watch: {
    $props: {
      handler() {
        this.parseData();
      },
      deep: true,
      immediate: true,
    },
  },

Key point to take away from this example is to use deep: true so it not only watches $props but also it's nested values like e.g. props.myProp

You can learn more about this extended watch options here: https://vuejs.org/v2/api/#vm-watch

Solution 4 - Javascript

You need to understand, the component hierarchy you are having and how you are passing props, definitely your case is special and not usually encountered by the devs.

> Parent Component -myProp-> Child Component -myProp-> Grandchild > Component

If myProp is changed in parent component it will be reflected in the child component too.

And if myProp is changed in child component it will be reflected in grandchild component too.

So if myProp is changed in parent component then it will be reflected in grandchild component. (so far so good).

Therefore down the hierarchy you don't have to do anything props will be inherently reactive.

Now talking about going up in hierarchy

If myProp is changed in grandChild component it won't be reflected in the child component. You have to use .sync modifier in child and emit event from the grandChild component.

If myProp is changed in child component it won't be reflected in the parent component. You have to use .sync modifier in parent and emit event from the child component.

If myProp is changed in grandChild component it won't be reflected in the parent component (obviously). You have to use .sync modifier child and emit event from the grandchild component, then watch the prop in child component and emit an event on change which is being listened by parent component using .sync modifier.

Let's see some code to avoid confusion

Parent.vue

<template>
	<div>
	<child :myProp.sync="myProp"></child>
    <input v-model="myProp"/>
	<p>{{myProp}}</p>
</div>
</template>

<script>
	
	import child from './Child.vue'

	export default{
		data(){
			return{
				myProp:"hello"
			}
		},
		components:{
			child
		}
	}
</script>

<style scoped>
</style>

Child.vue

<template>
<div>	<grand-child :myProp.sync="myProp"></grand-child>
	<p>{{myProp}}</p>
</div>

</template>

<script>
	import grandChild from './Grandchild.vue'
	
	export default{
		components:{
			grandChild
		},
		props:['myProp'],
		watch:{
			'myProp'(){
				this.$emit('update:myProp',this.myProp)
				
			}
		}
	}
</script>

<style>
	
</style>

Grandchild.vue

<template>
	<div><p>{{myProp}}</p>
	<input v-model="myProp" @input="changed"/>
	</div>
</template>

<script>
	export default{
		props:['myProp'],
		methods:{
			changed(event){
				this.$emit('update:myProp',this.myProp)
			}
		}
	}
</script>

<style>
	
</style>

But after this you wont help notice the screaming warnings of vue saying

> 'Avoid mutating a prop directly since the value will be overwritten > whenever the parent component re-renders.'

Again as I mentioned earlier most of the devs don't encounter this issue, because it's an anti pattern. That's why you get this warning.

But in order to solve your issue (according to your design). I believe you have to do the above work around(hack to be honest). I still recommend you should rethink your design and make is less prone to bugs.

I hope it helps.

Solution 5 - Javascript

for two way binding you have to use .sync modifier

<child :myprop.sync="text"></child>

more details...

and you have to use watch property in child component to listen and update any changes

props: ['myprop'],
  watch: { 
  	myprop: function(newVal, oldVal) { // watch it
      console.log('Prop changed: ', newVal, ' | was: ', oldVal)
    }
  }

Solution 6 - Javascript

Not sure if you have resolved it (and if I understand correctly), but here's my idea:

If parent receives myProp, and you want it to pass to child and watch it in child, then parent has to have copy of myProp (not reference).

Try this:

new Vue({
  el: '#app',
  data: {
    text: 'Hello'
  },
  components: {
    'parent': {
      props: ['myProp'],
      computed: {
        myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
      }
    },
    'child': {
      props: ['myProp'],
      watch: {
        myProp(val, oldval) { now val will differ from oldval }
      }
    }
  }
}

and in html:

<child :my-prop="myInnerProp"></child>

actually you have to be very careful when working on complex collections in such situations (passing down few times)

Solution 7 - Javascript

I work with a computed property like:

    items:{
    	get(){
    		return this.resources;
    	},
    	set(v){
    		this.$emit("update:resources", v)
    	}
    },

Resources is in this case a property:

props: [ 'resources' ]

Solution 8 - Javascript

Props and v-model handling. How to pass values from parent to child and child to parent.

Watch is not required! Also mutating props in Vue is an anti-pattern, so you should never change the prop value in the child or component. Use $emit to change the value and Vue will work as expected always.

/* COMPONENT - CHILD */
Vue.component('props-change-component', {
  props: ['value', 'atext', 'anumber'],
  mounted() {
    var _this = this
    
    this.$emit("update:anumber", 6)
    
    setTimeout(function () {
      // Update the parent binded variable to 'atext'
      _this.$emit("update:atext", "4s delay update from child!!")
    }, 4000)
    
    setTimeout(function () {
      // Update the parent binded v-model value
      _this.$emit("input", "6s delay update v-model value from child!!")
    }, 6000)
  },
  template: '<div> \
    v-model value: {{ value }} <br> \
    atext: {{ atext }} <br> \
    anumber: {{ anumber }} <br> \
    </div>'
})

/* MAIN - PARENT */
const app = new Vue({
  el: '#app',
  data() {
    return {
      myvalue: 7,
      mynumber: 99,
      mytext: "My own text",
    }
  },
  mounted() {
    var _this = this
    
    // Update our variable directly
    setTimeout(function () {
      _this.mytext = "2s delay update mytext from parent!!"
    }, 2000)
  },
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <props-change-component
    v-model='myvalue'
    :atext.sync='mytext'
    :anumber.sync='mynumber'>
    
  </props-change-component>
  
</div>

Solution 9 - Javascript

For me this is a polite solution to get one specific prop(s) changes and create logic with it

I would use props and variables computed properties to create logic after to receive the changes

export default {
name: 'getObjectDetail',
filters: {},
components: {},
props: {
  objectDetail: { // <--- we could access to this value with this.objectDetail
    type: Object,
    required: true
  }
},
computed: {
  _objectDetail: {
    let value = false
    // ...
    // if || do || while -- whatever logic
    // insert validation logic with this.objectDetail (prop value)
    value = true
    // ...
    return value 
  }
}

So, we could use _objectDetail on html render

<span>
  {{ _objectDetail }}
</span>

or in some method:

literallySomeMethod: function() {
   if (this._objectDetail) {
   ....
   }
}

Solution 10 - Javascript

Interesting observation for some use cases.

If you watch a data item from your store via a prop and you change the data item multiple times in the same store mutation it will not be watched.

However if you separate the data item changes into multiple calls of the same mutation it will be watched.

  • This code will NOT trigger the watcher:

    // Somewhere in the code:
    this.$store.commit('changeWatchedDataItem');
    
    // In the 'changeWatchedDataItem' mutation:
    state.dataItem = false;
    state.dataItem = true;
    
  • This code WILL trigger the watcher at each mutation:

    // Somewhere in the code:
    this.$store.commit('changeWatchedDataItem', true);
    this.$store.commit('changeWatchedDataItem', false);
    
    // In the 'changeWatchedDataItem' mutation:
    changeWatchedDataItem(state, newValue) {
        state.dataItem = newValue;
    }
    

Solution 11 - Javascript

I think that in most cases Vue updates component's DOM on a prop change.

If this is your case then you can use beforeUpdate() or updated() hooks (docs) to watch props.

You can do it if you're only interested in newVal and don't need oldVal

new Vue({
  el: '#app',
  data: {
    text: ''
  },
  components: {
    'child': {
      template: `<p>{{ myprop }}</p>`,
      props: ['myprop'],
      beforeUpdate() {
        console.log(this.myprop)
      },
      updated() {
        console.log(this.myprop)
      }
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <child :myprop="text"></child>
  <input v-model="text" placeholder="Type here to view prop changes" style="width:20em">
</div>

Solution 12 - Javascript

The watch function should place in Child component. Not parent.

Solution 13 - Javascript

You can use the watch mode to detect changes:

Do everything at atomic level. So first check if watch method itself is getting called or not by consoling something inside. Once it has been established that watch is getting called, smash it out with your business logic.

watch: { 
  myProp: function() {
   console.log('Prop changed')
  }
}

Solution 14 - Javascript

@JoeSchr has an answer. Here is another way to do if you don't want deep: true

 mounted() {
    this.yourMethod();
    // re-render any time a prop changes
    Object.keys(this.$options.props).forEach(key => {
      this.$watch(key, this.yourMethod);
    });
  },

Solution 15 - Javascript

I use props and variables computed properties if I need create logic after to receive the changes

export default {
name: 'getObjectDetail',
filters: {},
components: {},
props: {
    objectDetail: {
      type: Object,
      required: true
    }
},
computed: {
    _objectDetail: {
        let value = false
        ...

        if (someValidation)
        ...
    }
}

Solution 16 - Javascript

If your prop myProp has nested items, those nested won't be reactive, so you'll need to use something like lodash deepClone :

<child :myProp.sync="_.deepClone(myProp)"></child>

That's it, no need for watchers or anything else.

Solution 17 - Javascript

My below answer is applicable if someone using Vue 2 with composition API. So setup function will be

setup: (props: any) => {
  watch(() => (props.myProp), (updatedProps: any) => {
    // you will get the latest props into updatedProp
  })
}

However, you will need to import the watch function from the composition API.

Solution 18 - Javascript

By default props in the component are reactive and you can setup watch on the props within the component which will help you to modify functionality according to your need. Here is a simple code snippet to show how it works

setup(props) {
 watch(
  () => props.propName,
  (oldValue, newValue) => {
    //Here you can add you functionality 
    // as described in the name you will get old and new value of watched property
  },
  { deep: true },
  { immediate: true } //if you need to run callback as soon as prop changes
)
}

Hope this helps you to get the result you want out of this. Have a great day.

Solution 19 - Javascript

if myProp is an object, it may not be changed in usual. so, watch will never be triggered. the reason of why myProp not be changed is that you just set some keys of myProp in most cases. the myProp itself is still the one. try to watch props of myProp, like "myProp.a",it should work.

Solution 20 - Javascript

props will be change if you add

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmio.ioView Question on Stackoverflow
Solution 1 - JavascriptEgor StambakioView Answer on Stackoverflow
Solution 2 - JavascriptBearInBoxView Answer on Stackoverflow
Solution 3 - JavascriptJoeSchrView Answer on Stackoverflow
Solution 4 - JavascriptAnkit Kumar OjhaView Answer on Stackoverflow
Solution 5 - JavascriptMahamudul HasanView Answer on Stackoverflow
Solution 6 - Javascriptm.cichaczView Answer on Stackoverflow
Solution 7 - JavascriptWouter SchoofsView Answer on Stackoverflow
Solution 8 - JavascriptHeroselohimView Answer on Stackoverflow
Solution 9 - JavascriptManuel AlanisView Answer on Stackoverflow
Solution 10 - JavascriptValentine ShiView Answer on Stackoverflow
Solution 11 - JavascriptIlyichView Answer on Stackoverflow
Solution 12 - JavascriptCong NguyenView Answer on Stackoverflow
Solution 13 - JavascriptRahul SharmaView Answer on Stackoverflow
Solution 14 - JavascriptAlvin SmithView Answer on Stackoverflow
Solution 15 - JavascriptManuel AlanisView Answer on Stackoverflow
Solution 16 - JavascriptMaxView Answer on Stackoverflow
Solution 17 - JavascriptKiran MahaleView Answer on Stackoverflow
Solution 18 - JavascriptkshitijView Answer on Stackoverflow
Solution 19 - JavascriptadockingView Answer on Stackoverflow
Solution 20 - JavascriptChandra sekhar mohantyView Answer on Stackoverflow