Reputation: 573
The problem here is simple to ilustrate, I'm executing a method on the parent component, which changes the value of a property of my object products
(also belonging to the parent data
), this is working fine.
But i'm passing this object as a prop to a child component and watching it deeply <- this is failing, as you can see the alert('changed');
is never executed:
Vue.component('child', {
props: ['prods'],
watch: {
prods: {
handler: function(new_val, old_val) {
alert('watched');
},
deep: true
}
}
})
new Vue({
el: '#app',
template: '<div>{{products[0].value}}<br><button v-on:click="incre">increment prod 0</button></div>',
data: {
products: [
{id: 1, name: 'prod1', value: 20},
{id: 2, name: 'prod2', value: 40},
],
},
methods: {
incre: function() {
this.products[0].value += 20;
}
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<child v-bind:prods="products"></child>
</div>
https://jsfiddle.net/dmbgmxzh/6/
(Update):
this works: https://jsfiddle.net/dmbgmxzh/5/
this doesn't: https://jsfiddle.net/dmbgmxzh/6/
This is strange...
Upvotes: 0
Views: 216
Reputation: 2322
As an alternative, you could pass product as a prop to your child component, watching each product separately. Like this:
Vue.component('child', {
props: ['product'],
watch: {
product: {
handler: function (new_val, old_val) {
alert('watched');
},
deep: true
}
}
})
new Vue({
el: '#app',
data: {
products: [
{
id: 1,
name: 'prod1',
value: 20
},
{
id: 2,
name: 'prod2',
value: 40
},
],
},
methods: {
incre: function () {
this.products[0].value += 20;
}
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<div>{{products[0].value}}<br><button v-on:click="incre">increment prod 0</button></div>
<child :product="product" v-for="product in products"></child>
</div>
See this post also.
Upvotes: 2