【问题标题】:Adding component dynamically in Ember在 Ember 中动态添加组件
【发布时间】:2016-01-13 17:32:16
【问题描述】:

使用 余烬:1.13.11, 灰烬数据:1.13.8, ember-cli:1.13.12

我想向网页动态添加一个组件 - 这个网页是另一个组件的模板,不要认为它会产生任何影响 -。这是我的代码 sn-p,在其中我尝试将名为 LyricsEditorLine 的组件添加到 <div> 标签,有点像 this

agenda-alpha/components/lyrics-editor.js

import Ember from 'ember';
import LyricsEditorLine  from 'agenda-alpha/components/lyrics-editor-line';

export default Ember.Component.extend({
   afterRenderEvent:function(){
      LyricsEditorLine.create().appendTo($("#in"));
 },
init:function(){
  Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
  this._super();
 }
});

agenda-alpha/templates/components/lyrics-editor.hbs

<div id='in'> </div>

每次都这样

 'Uncaught Error: Assertion Failed: You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead'

ContainerViewhere发现是deprecated 我发现的大多数答案都没有使用 ember-cli,而且作为初学者更难理解

我希望能够根据用户的需要添加组件

【问题讨论】:

  • 简短的回答是,如果没有一些潜在的不良副作用,您将无法做到这一点。为什么不能只使用 Handlebars {{#if}} 帮助器来动态渲染组件?
  • 未定义要添加的组件数量。这取决于用户的需求
  • 你仍然可以在 Handlebars 中做到这一点,你只需要使用某种循环(有几种方法可以做到)。一般来说,你可以用 jQuery 做的几乎所有事情都可以使用 Handlebars 和计算/存储的属性来实现。
  • 这一切都在 Ember 指南中。 Here's a guide on rendering a list of items。如果您发现自己在没有 jQuery 的情况下难以应付,那么您可能会遗漏一些关键特性。如果可以的话,我会一直阅读指南。基于模板的渲染与您习惯的有很大不同,但它更强大。
  • 很抱歉。我链接到最新版本,但左上角有一个下拉菜单可以更改文档版本。 Here's the corresponding guide for 1.13.

标签: ember.js ember-cli


【解决方案1】:

我想你可能想要{{component}} 助手,它允许dynamically render a component

{{component "componentName" param1=paramValue param2=anotherParamValue}}

这意味着你可以拥有(编造的例子)

{{component "lyrics-editor-line" line=line}}

最好的一点是componentName 可以是绑定属性

{{component componentName line=line}}

在你的控制器/组件中:

componentName: Ember.computed('prop1','prop2', function() {
  if (this.get('prop1') === 'A') {
    return 'my-component-a';
  }
  return 'default-component';
}),

line: computed('prop3', function() {
   return this.get('prop2');
})

此外,您可以在每个循环中包含组件助手(示例取自 Ember 文档)

{{#each model as |post|}}
  {{!-- either foo-component or bar-component --}}
  {{component post.componentName post=post}}
 {{/each}}

【讨论】:

  • 感谢您的回答 Pedro,但您提供的只是 .hbs 文件中已经存在的组件,但我希望用户能够添加任意数量的组件,或者根本不添加在运行时,例如将商品添加到购物车中,您的回答使其只有一个组件,并且在循环的情况下,我尝试将组件添加到模型数组但它不起作用
  • 该组件需要存在于您的 ember 应用程序中,而不是存在于那个特定的 .hbs 文件中......否则它不会很有用。只要该组件在您的应用程序中可用,您就可以使用 component 帮助器来显示该组件。我不明白您所说的“将组件添加到模型数组”是什么意思。组件仅存在于模板中,您的模型用于您的数据。您使用数据来选择要渲染的内容。并使用组件来呈现该数据。
  • 是的,你是对的,我只是把所有这些组件都弄错了,我认为我必须在控制器端创建组件,然后将其附加到 DOM,而不仅仅是更新数组被发送到 {{each}} 助手。
  • 很高兴我帮助您了解了有关 ember 的更多信息。这并不容易,但值得。继续使用您的 ember 应用程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 2017-12-14
  • 2017-09-30
相关资源
最近更新 更多