[英]How to listen parent component value change in child component ember octane?
This is my code这是我的代码
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);
}
});
}
}
I wanted to observe this.args.changes in my child compoent.我想观察我的孩子组件中的 this.args.changes。 How can I do that in ember-octane way?
我怎样才能以 ember-octane 的方式做到这一点?
I'm assuming that you are using the latest Octane features in you app from your code snippet.我假设您在您的代码片段中的应用程序中使用了最新的 Octane 功能。
We can make a class property reactive using the @tracked
decorator.我们可以使用
@tracked
装饰器使 class 属性反应。 By this, when a tracked value changes in the parent component, the same change will be propogated into all the places where its being utilized.这样,当父组件中的跟踪值发生更改时,相同的更改将传播到所有使用它的地方。 In your case, you have passed the value into child component and thus, the changes will also tracked inside the child component.
在您的情况下,您已将值传递给子组件,因此,更改也将在子组件内跟踪。
parent component class:父组件 class:
export class ParentComponent extends Component {
@tracked changes = [1,2,3];
@action addChanges() {
this.changes = [...this.changes, this.changes.length]
}
}
In you child component you can use getters to recompute the changes accordingly.在您的子组件中,您可以使用 getter 相应地重新计算更改。 getter will be recomputed on every time a value accessed inside the getter changes.
每次在 getter 中访问的值发生变化时,都会重新计算 getter。 For instance, from your code, if you need to get the sum of the array,
例如,从您的代码中,如果您需要获取数组的总和,
child component class:子组件 class:
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);
}
}
child template:子模板:
SUM: {{this.sum}}
EDIT编辑
If you need to run an arbitrary function when a value changes (most to be used to sync with external libraries or manual DOM mutations), you can use {{did-update}}
modifier of ember-render-modifiers如果您需要在值更改时运行任意 function(大多数用于与外部库同步或手动 DOM 突变),您可以使用ember-render-modifiers的
{{did-update}}
修饰符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.