Vue.js Vuejs-在';这';非我

Vue.js Vuejs-在';这';非我,vue.js,vuejs2,Vue.js,Vuejs2,我观察嵌套对象。但数据属性未定义 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),300

我观察嵌套对象。但数据属性未定义

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

当使用嵌套的监视语句(例如
object.parameter
)时,应使用常规函数而不是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
    },
  },
});

使用常规Vue方法:

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

避免在Vue实例中使用
箭头函数
,而是使用创建函数。@Nguyễ恩唐图,哦,谢谢。我不知道。解决了的。