我有一个带有占位符和按钮的组件。每当单击此按钮时,我都希望实例化一个子组件并将其添加到占位符div中。这就像在点击按钮时添加行一样。我如何实现这个行为。
下面是伪代码。
MainCompoent.hbs
<div id="placeHolder> </div>
<button onClick={{this.clickAdd}}> Add </button>
MainCompoent.js
@action
clickAdd() {
//How to initialize Row Component and add to the placeHolder
}
RowComponent.hbs
<div>
<input name>
<input age>
</div>
我尝试了这样的东西,但它并没有像预期的那样工作。
MainComponent.js
@action
addCondition (){
document.getElementById("placeholder").innerHTML += `<RowComponent/>`;
}

发布于 2020-01-20 13:49:24
在任何前端框架中,通常都不推荐直接操作DOM (如您的MainComponent.js片段中所述),因为框架本身将有效地管理DOM。Ember的模板在设计上是声明性的,因此这个用例可以很容易地在模板中表达。
由于您需要多次动态处理组件的呈现,这类似于在javascript中多次控制台记录变量。我们需要在初始化循环上下文之后执行loop them in the template操作,以便首先拥有单个条目。每次用户点击Add按钮时,我们都可以动态地推送一个新条目。
伪代码如下所示:
MainComponent.js
@tracked rows = [{ name: '', phone: '' }];
@action
clickAdd() {
this.rows.push({ name: '', phone: '' });
this.rows = this.rows; // to re-render the template
}MainComponent.hbs
{{#each this.rows as |row|}}
<RowComponent @row={{row}} />
{{/each}}
<button onClick={{this.clickAdd}}> Add </button>希望这能有所帮助。
https://stackoverflow.com/questions/59816784
复制相似问题