javascript - 如何在子组件 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 的方式做到这一点?
解决方案
我假设您在您的代码片段中的应用程序中使用了最新的 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}}
修饰符
推荐阅读
- java - 如何在 pom.xml 中的 Maven Jetty 插件中设置 web.xml 的路径?
- php - 无法使用 Symfony 4.1 创建数据库:找不到驱动程序
- c# - 在 for 循环打字稿和休眠死锁中调用异步函数
- flutter - 水平扩展以适应文本内容的文本字段
- kotlin - 如何从 lambda 引用外部函数?
- java - uso e declaração de namespace Saxon em codigo java
- c++ - 访问映射中的分区向量
- javascript - JavaScript 表单验证 - 日期
- javascript - 如何删除 logo.png 周围的框?
- graph - Twitter 的中介中心性是否同时考虑了关注者和关注者?