首页 > 解决方案 > 如何在子组件 ember octane 中监听父组件值的变化?

问题描述

这是我的代码

parent.hbs
 
 <ChildComp
   @value={{this.changes}}
 />


parent.js
export class ParentComponet extends Component {
  @tracked this.changes = [1,2,3]
  
  @action addChanges() {
     this.changes = [...this.changes, this.changes.length]
  }
}

child-comp.js
export class ChildComponet extends Component {
   // I wanted to observe this.args.changes updated
   // Based on that I need to call some operation
   get operation() {
      let parent = this.args.values.map((obj) {
            if (obj.parent !== null) {
             set(obj, 'goal', null);
             set(obj, 'newSubGoal', null);
            }
    });
   }
}

我想观察我的孩子组件中的 this.args.changes。我怎样才能以 ember-octane 的方式做到这一点?

标签: javascriptember.jsember-dataember-cliember-octane

解决方案


我假设您在您的代码片段中的应用程序中使用了最新的 Octane 功能。

@tracked我们可以使用装饰器使类属性具有反应性。这样,当父组件中的跟踪值发生更改时,相同的更改将传播到所有使用它的地方。在您的情况下,您已将值传递给子组件,因此,更改也将在子组件内跟踪。

父组件类:

export class ParentComponent extends Component {
  @tracked changes = [1,2,3];
  
  @action addChanges() {
     this.changes = [...this.changes, this.changes.length]
  }
}

在您的子组件中,您可以使用 getter 相应地重新计算更改。每次在 getter 中访问的值发生变化时,都会重新计算 getter。例如,从您的代码中,如果您需要获取数组的总和,

子组件类:

export class ChildComponent extends Component {
   // This getter will be computed every time the `changes` array changes.
   get sum() {
     return this.args.value.reduce((a, b) => a + b, 0);
   }
}

子模板:

SUM: {{this.sum}}

编辑

如果您需要在值更改时运行任意函数(大多数用于与外部库同步或手动 DOM 突变),您可以使用ember-render-modifiers 的{{did-update}}修饰符


推荐阅读