0

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

2
  • avoid using arrow function in Vue instance, create a function using function declaration instead. Commented Oct 2, 2018 at 9:33
  • @NguyễnThanhTú, oh thanks. I didn't know that. solved. Commented Oct 2, 2018 at 10:04

2 Answers 2

1

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
    },
  },
});
Sign up to request clarification or add additional context in comments.

Comments

0

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
    }
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.