使用 Aurelia <content> 元素

Using the Aurelia <content> element

我正在尝试创建一个自定义元素,允许用户在创建元素时指定元素的内容,如下所示:

<custom-element title="Hello">
    <p>Lorem ipsum dolor sit amet.</p>
    <p>Lorem ipsum dolor sit amet.</p>
    <p>Lorem ipsum dolor sit amet.</p>
</custom-element>

我的自定义元素基本上是这样的:

<template>
    <div class="my-custom-element">
        <h2 if.bind="title">${title}</h2>
        <content></content>
    </div>
</template>

我完全猜到了 <content> 元素的用途,它看起来并不像这样工作。我也找不到任何文档。我看到其他人将它与 select 属性一起使用,该属性指向自定义元素内容 内部 的特定元素,但我想访问其中的所有内容 - 而不是特定元素。

我做错了什么?

Aurelia 使用 <slot> 元素在自定义元素中呈现内容。您可以在 documentation hub, or take a look at blog post where they explain the reasoning for <slot> elements. Basically, it's a part of Shadow DOM v1 specification 中阅读相关内容,Aurelia 团队会尽可能地遵循标准。

<slot> 的一个很酷的地方是你可以在你的自定义元素中有多个命名的元素,这在上面的 post 中有解释。

因此,您的自定义元素将如下所示:

<template>
    <div class="my-custom-element">
        <h2 if.bind="title">${title}</h2>
        <slot></slot>
    </div>
</template>

当然,这意味着您需要使用较新版本的 Aurelia,因为它已在 5 月底的某个时候添加。