简体   繁体   English

如何在 Ember Octane 中通过 javascript 向主组件添加子组件

[英]How to add a child component to the main component through javascript in Ember Octane

I have a component with a placeholder and button.我有一个带有占位符和按钮的组件。 Whenever this button is clicked I want to instantiate and add a child component to the placeholder div.每当单击此按钮时,我都想实例化并将子组件添加到占位符 div。 It's like adding rows on button click.这就像在按钮单击时添加行。 How do I implement this behaviour.我如何实现这种行为。

Here is the pseudo code.这是伪代码。

 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>

I tried something like this but it did not work as expected.我尝试了这样的事情,但没有按预期工作。

MainComponent.js

@action
addCondition (){       
    document.getElementById("placeholder").innerHTML += `<RowComponent/>`;
}

在此处输入图片说明

Direct DOM manipulation (as mentioned in your MainComponent.js snippet) is generally not recommended in any of the frontend frameworks as the framework itself will manages the DOM efficiently.在任何前端框架中通常都不推荐直接 DOM 操作(如您的MainComponent.js片段中所述),因为框架本身将有效地管理 DOM。 Ember's templates are declarative by design and hence this use case can be expressed in the template easily. Ember 的模板在设计上是声明性的,因此这个用例可以很容易地在模板中表达。

Since you need to work with the rendering of a component multiple times dynamically, it's similar to console logging the a variable multiple times in javascript.由于您需要多次动态处理组件的渲染,因此它类似于在 javascript 中多次控制台记录 a 变量。 We need to loop them in the template after initializing the looping context to have a single entry at first.我们需要在初始化循环上下文后在模板中循环它们以首先具有单个条目。 We can dynamically push a new entry every time the user hits the Add button.我们可以在用户每次点击添加按钮时动态推送一个新条目。

The pseudo-code would be like:伪代码如下:

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>

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM