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 simi
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.
The watch function should place in Child component. Not parent.
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' ]
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>
@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);
});
},
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)
}
}