【问题标题】:How to verify that a specific contextual component is present in template?如何验证模板中是否存在特定的上下文组件?
【发布时间】:2019-11-29 03:42:31
【问题描述】:

在 Ember.js 中,我正在设计一个上下文组件,并希望处理不存在子组件的情况并改为显示一些通用信息。

但我不知道如何检测标签何时出现在模板中。 使用yield和hash,如果标签不存在,什么都不会显示,仅此而已...

第一种情况:所有子组件都存在

<ParentComponent as |parent|>
  <parent.mandatoryChild>
    Something
  </parent.mandatoryChild>
  <parent.child>
    Something else
  </parent.child>
</ParentComponent>

第二种情况:parent.child 组件不存在

<ParentComponent as |parent|>
  <parent.mandatoryChild>
    Something
  </parent.mandatoryChild>
  {{! no parent.child here }}
</ParentComponent>

我的父组件模板是:

<div class="mandatoryChild-wrapper-class">
{{yield
        (hash
              mandatoryChild=(component this.mandatoryChildComponent)
        )
}}
</div>
<div class="child-wrapper-class">
<!-- how to show some generic information when child is not present in the callee template? -->
{{yield
        (hash
              child=(component this.childComponent)
        )
}}
</div>

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    有不同的模式可以做到这一点。

    最简单的方法是在父组件上使用参数。在这种情况下,消费者决定呈现可选的孩子,例如:&lt;ParentComponent @withOptionalChild={{true}} /&gt;

    您还可以使用更高级的解决方案。例如。如果已注册,可选子组件可以在父组件上注册自己,如果它被删除,则可以取消注册。您应该设置对消费者透明的注册。例如。通过将registerunregister 参数传递给产生的可选子级,该子级在didInsertElementwillDestroyElement 挂钩中调用那些。请注意,使用该解决方案,可选子组件不会在与父组件相同的 runloop 中呈现,而是稍后在一个 runloop 中呈现。这对用户来说可能是闪烁的。它还可能引入其他时间问题。

    我猜这些是该场景中最常见的模式。第一个例子是Ember Contextual Table。它使用defaultHeader 属性来控制用户是否能够自定义组件块形式的标题。第二种模式的一个非常高级的例子是Ember Leaflet

    在大多数情况下,我会推荐这个论点。它可能会添加一些样板,但它更容易实现和维护。

    【讨论】:

      【解决方案2】:
      <div class="mandatoryChild-wrapper-class">
        {{yield (hash mandatoryChild=(component this.mandatoryChildComponent))}}
      </div>
      <div class="mandatoryChild-wrapper-class">
        {{#if this.showOptionalChild}}
          {{yield (hash child=(component this.childComponent))}}
        {{else}}
          generic information
        {{/if}}
      </div>
      

      【讨论】:

      • 但是this.childComponent只是一个包含子组件名称的字符串。所以它永远是非空的......
      猜你喜欢
      • 2018-11-15
      • 2016-03-03
      • 2013-05-21
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 2011-03-02
      相关资源
      最近更新 更多