访问嵌套组件中的父属性

Accessing Parent Properties in Nested Components

由于预期可路由组件即将推出,我正尝试在我的 Ember 2.0 应用程序中尽可能使用组件。我 运行 遇到了一个令人困惑的问题,当以块形式提供时,我无法从模板访问父组件的属性。这可能是不可能的,但我想确定一下。这是一个例子:

模板:

// templates/approvals.hbs
{{#x-secure/schedule/approvals}}

  {{#x-secure/layout/full sectionTitle=sectionTitle sectionDescription=sectionDescription}}
    ...
  {{/x-secure/layout/full}}

{{/x-secure/schedule/approvals}}

组件模板:

// templates/components/schedule/approvals.hbs
{{yield}}

组件:

// components/schedule/approvals.js
import Ember from 'ember';

export default Ember.Component.extend({

  /////////////////////////////////////
  // PROPERTIES
  /////////////////////////////////////

  sectionTitle: 'Scheduling: Approvals',
  sectionDescription: 'Lots of magical , fanstastic stuff.'

});

我遇到的问题是我无法从父组件 (approvals) 访问 sectionTitlesectionDescription 并将其传递到 layout/full 零件。但是,如果我从组件块中删除代码并将其移至 templates/components/schedule/approvals.hbs 模板,它会按预期工作。只是无法从组件的块形式访问父组件的属性吗?

谢谢!

确实不可能。组件的属性在组件的模板中可用,但在实例化组件的模板中不可用。

如果您需要组件来提供可用的东西,它应该显式地产生它们:

// templates/components/schedule/approvals.hbs
{{yield sectionTitle sectionDescription}}

并使用组件:

// templates/approvals.hbs
{{#x-secure/schedule/approvals as |title description|}}

  {{#x-secure/layout/full sectionTitle=title sectionDescription=description}}
    ...
  {{/x-secure/layout/full}}

{{/x-secure/schedule/approvals}}

注意 as |x y ...| 表示法来为产生的值分配名称。

任何东西都可以通过这种方式产生,包括this(但要小心,这会破坏封装)和动作。