Vuejs - watch nested object in 'this' not self

时间:2018-10-02 09:17:42

标签: vue.js vuejs2

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 个答案:

答案 0 :(得分: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
    },
  },
});

答案 1 :(得分:0)

使用常规Vue方法:

year