Vue道具是对象。变更检测不起作用

Pet*_*sko 1 javascript oop vue.js

我想请您解释以下情况。

我有一个对象,其中包含其他对象。我将此对象作为道具传递给vue组件。

classs parent {

     constructor () {
        this.child = new Child();
     }

}
Run Code Online (Sandbox Code Playgroud)

然后,更改子对象的属性。但是,以下vue代码没有任何作用,并且似乎甚至没有调用watch方法。

    watch : {
        property : {
            handler (newVal) {
                console.log('property updated');
            },
            deep: true
        }

    },
Run Code Online (Sandbox Code Playgroud)

由于vue道具实际上是对父对象的引用,因此将其更改。现在,如果孩子发生变化,我如何检测父母的变化?

Roy*_*y J 5

如果您要更改的数据项在成为Vue数据之前就已经存在,则可以很好地工作。换句话说,只有Vue在构建实例时才知道的是反应性的项目。

Vue无法检测到属性添加。如果要添加一个孩子或一个孩子的成员,则需要$set通过分配给已经反应的元素来使用或进行更改。

class Child {
  constructor() {
    this.a = 'one';
  }
}

class Parent {
  constructor() {
    this.child = new Child();
  }
}

new Vue({
  el: '#app',
  data: {
    p: new Parent()
  },
  watch: {
    p: {
      handler(newVal) {
        console.log('property updated', newVal);
      },
      deep: true
    }
  },
  mounted() {
    setTimeout(() => {
      this.p.child.a = 'two';
    }, 500);
    setTimeout(() => {
      this.$set(this.p.child, 'b', 'something completely new');
    }, 2500);
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">

</div>
Run Code Online (Sandbox Code Playgroud)