Reputation: 1466
I want to use watch for a props on a child component, but it's not working.
Here is my code :
props: {
searchStore: {
type: Object
}
},
watch: {
searchStore(newValue) {
alert('yolo')
console.log(newValue)
}
And it's unfortunately not working
I've looked on this post and tried everything and nothing work : VueJs 2.0 - how to listen for `props` changes
I checked my props with Vue Devtools and it's changing.
Thanks in advance to the community !
Upvotes: 21
Views: 39774
Reputation: 35724
based on that code, it should work, so the issue may be somewhere else. Can you post more code?
if you want to run immediately, you can use immediate
. This is the syntax:
watch: {
searchStore: {
immediate: true,
deep: true,
handler(newValue, oldValue) {
}
}
},
The deep: true
setting will deep-watch for a change within the object.
When you are updating parts of this object in the parent component, make sure you use Vue's $set
function.
this.$set(this.searchStore, 'myKey', {price: 12.22});
further reading: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
Upvotes: 36
Reputation: 1168
Could be that 'searchStore' wasn't changing?
Since its an object, vue is watching for a new reference of an object to be passed.
Meaning (will not trigger watch):
roorSearchStore.a= newVal
will not trigger the watch (since the reference didn't change).
You could watch deep like Daniel says, Or do Object.assign like this:
rootSearchStore = Object.assign ({},roorSearchStore,{a:newVal}).
Or try to watch a timestamp of the changes in rootSearchStore .
Upvotes: 0