【问题标题】:Ember template - pass parameters from child to parent in function callEmber 模板 - 在函数调用中将参数从子级传递给父级
【发布时间】:2022-08-09 00:47:30
【问题描述】:
我有一个循环创建的 Ember 组件。我用参数传递一个函数。孩子需要传递另一个参数才能使函数工作。我如何实现这一目标?
前任:
Parent:
<div>
{{#each items as |item index|}}
<Child
@onButton1Click={{fn this.doStuff index}} // need index to do stuff
/>
{{/each}}
</div>
Child:
<div>
<ColorSelector @onColorChange={{this.changeColor}}/>
<Button @onClick={{this.onButton1ClickAction}} />
</div>
// Parent.js
@action
doStuff(index, color) {
// calculate stuff using color and index
}
// Child.js
@tracked
color = \'blue\';
@action
changeColor(passedColor) {
this.color = passedColor; // some hex value
}
@action
onButton1ClickAction() {
this.args.onButton1Click?.(this.color);
// how do I pass back color
}
问题是,我怎样才能使用来自孩子的传递颜色并保持来自父母的索引?目前只看到索引。
标签:
javascript
ember.js
handlebars.js
【解决方案1】:
好像
<Child
onButton1Click={{fn this.doStuff index}} // need index to do stuff
/>
应该
<Child
@onButton1Click={{fn this.doStuff index}} // need index to do stuff
/>
和
<ColorSelector onColorChange={{this.changeColor}}/>
<Button onClick={{this.onButton1ClickAction}} />
应该
<ColorSelector @onColorChange={{this.changeColor}}/>
<Button @onClick={{this.onButton1ClickAction}} />
(注意@)
如果没有@,onButton1Click 将被解释为 html 属性,它将应用于带有...attributes(如果存在)的Child 中的元素,否则onButton1Click 不会做任何事情。
相关文档:https://guides.emberjs.com/release/components/component-arguments-and-html-attributes/
【解决方案2】:
我认为你只需要从孩子那里执行父功能
//child.js
@tracked
color = 'blue';
@action
changeColor(passedColor) {
this.color = passedColor; // some hex value
}
@action
onButton1ClickAction() {
const click = this.args.onButton1Click ?? null;
if (click) {
click(this.color)
}