是否可以在轻型DOM中声明插槽名称?

时间:2016-12-23 23:23:47

标签: javascript browser web-component shadow-dom

在shadow DOM v0中,开发人员不需要了解轻量级DOM内容放置在组件阴影区中的方式/位置的内部实现。

v0规范与<select><option>等内置组件的当前行为相匹配,消费者并不关心其特定元素内容的位置。相反,shadow DOM会自动选取与select标记上的<content>属性中指定的选择器匹配的元素,并将它们放在阴影树内的正确位置。这对于消费者开发人员的代码来说需要更少的样板。

在v1中,您需要具体了解插槽名称。模仿前面提到的<select>的相同示例,我需要使用类似<option slot="option">的内容,其中slot属性值指定放置当前元素的位置。我也可以添加那些不打算包含在该插槽中的元素,如<table slot="option">

总之,我的担忧是:

  1. 每次使用webcomponent时都需要指定额外信息
  2. 能够将无效元素添加到错误的阴影DOM位置并导致不可预测的副作用
  3. 在影子DOM v1中有没有办法获得<content select="option"></content>的旧行为,其中一个孩子必须匹配特定的选择器或者它被丢弃?如果没有,有没有人知道为什么特别是这样一个巨大的突破性变化?

    示例1 (v0规范)

    的index.html

    <my-component>
        <my-child-component>Text</my-child-component>
        <wrong-child-component>Wrong</wrong-child-component>
    </my-component>
    

    component.html(shadow DOM)

    <div>
        <content select="my-child-component"></component>
    </div>
    

    生成DOM

    <my-component>
        #shadow-root
            <div>
                <my-child-component>Text</my-child-component>
            </div>
    <my-component>
    

    示例2 (v1规范)

    的index.html

    <my-component>
        <my-child-component slot="child-slot">Text</my-child>
        <wrong-child-component slot="child-slot">Wrong</wrong-child-component>
    </my-component>
    

    component.html(shadow DOM)

    <div>
        <slot name="child-slot"></slot>
    </div>
    

    生成DOM

    <my-component>
        #shadow-root
            <div>
                <my-child-component>Text</my-child-component>
                <wrong-child-component>Wrong</wrong-child-component>
            </div>
    <my-component>
    

2 个答案:

答案 0 :(得分:3)

要过滤正确的元素,也许您可​​以在Shadow DOM CSS样式中使用::slotted( selector )伪元素:

<style>
    ::slotted( :not( option ) )
    {
        display: none;
    }
</style>
<slot></slot>

...只会显示<option>元素。

答案 1 :(得分:2)

对于v1slot没有其他替代品(据我所知)。但我仍然没有看到问题。就像content一样,您也可以使用无名插槽。

以下是Polymer's 2.0 migration guide

的示例
<!-- element template -->
<dom-module id="my-el">
  <template>
   ...
   <h2>
     <slot name="title"></slot>
   </h2>
   <div>
     <slot></slot>
   </div>
 </template>
</dom-module>

...
<!-- usage -->
<my-el>
   <span slot="title">Mr. Darcy</span>
   <span>Fun at parties.</span>
</my-el>

Here's关于github的讨论之一讨论提议使用插槽内容而只列出插槽内容的优点

  

默认插槽与默认插入点。在v0中,默认插入点(没有select属性的插入点)消耗与先前插入点不匹配的所有节点。在v1中,默认插槽(没有名称属性的插槽)仅匹配没有插槽属性的内容。换句话说,具有slot属性的节点永远不会分发到默认插槽。

虽然它对内容的缺点也很少,但至少目前供应商已经同意插槽是前进的方向。