【问题标题】:Vuejs - watch nested object in 'this' not selfVuejs - 在'this'而不是self中观察嵌套对象
【发布时间】:2018-10-02 09:17:41
【问题描述】:

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

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

【问题讨论】:

  • 避免在 Vue 实例中使用 arrow function,而是使用 function declaration 创建函数。
  • @NguyễnThanhTú,哦,谢谢。我不知道。解决了。​​

标签: vue.js vuejs2


【解决方案1】:

当使用嵌套的监视语句(例如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
    },
  },
});

【讨论】:

    【解决方案2】:

    使用常规的 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
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 1970-01-01
      • 2022-11-25
      • 2020-08-28
      • 2021-11-10
      • 2021-06-27
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      相关资源
      最近更新 更多