Reputation: 67
i watch nested object. but data property undefined.
const app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
item: {
foo: 'test',
},
},
//for test run, wait 3000ms
mounted(){
setTimeout(function(){
this.item.foo = 'a';
}.bind(this),3000);
},
watch: {
'item.foo': (newVal, oldVal) => {
console.log(newVal); // running
this.message='new Hello'; // but this.message undefined
},
},
});
https://codepen.io/anon/pen/LgpzLa
Upvotes: 0
Views: 124
Reputation: 14259
Using regular Vue methods:
const app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
item: {
foo: 'test',
},
},
//for test run, wait 3000ms
mounted(){
setTimeout(function(){
this.item.foo = 'a';
}.bind(this),3000);
},
watch: {
'item.foo': 'itemFooChanged'
},
},
methods:
{
itemFooChanged (newVal, oldVal)
{
console.log(newVal); // running
this.message='new Hello'; // this.message works
}
}
});
Upvotes: 0
Reputation: 2780
When using nested watch statements (e.g. object.parameter
) you should use regular functions instead of lambda;
const app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
item: {
foo: 'test',
},
},
//for test run, wait 3000ms
mounted(){
setTimeout(function(){
this.item.foo = 'a';
}.bind(this),3000);
},
watch: {
'item.foo': function(newVal, oldVal) {
console.log(newVal); // running
this.message='new Hello'; // but this.message undefined
},
},
});
Upvotes: 1