在shadow DOM v0中,开发人员不需要了解如何将light DOM内容放置在组件的阴影dom中的内部实现 .
v0规范与 <select>
和 <option>
等内置组件的当前行为相匹配,其中消费者并不关心具体放置元素内容的位置 . 相反,shadow DOM会自动选取与 <content>
标签上的 select
属性中指定的选择器匹配的元素,并将它们放在阴影树内的正确位置 . 这对于使用开发人员的代码来说需要更少的样板 .
在v1中,您需要具体了解插槽名称 . 模仿前面提到的与 <select>
相同的例子,我需要使用类似 <option slot="option">
的东西,其中slot属性值指定放置当前元素的位置 . 我也可以添加那些不打算包含在那个插槽中的元素,如 <table slot="option">
.
总之,我的担忧是:
-
每次使用webcomponent时都需要指定额外信息
-
能够将无效元素添加到错误的阴影DOM位置,并导致不可预测的副作用
In shadow DOM v1 is there a way to get the old behavior of <content select="option"></content> where a child has to match a specific selector or it is discarded? 如果没有,有谁知道为什么特别是这么大的突破性改变?
Example 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>
Example 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 回答
要过滤正确的元素,也许您可以在Shadow DOM CSS样式中使用::slotted( selector )伪元素:
...将仅显示
<option>
元素 .对于
v1
,slot
将没有其他替代品(据我所知) . 但我仍然没有看到问题 . 就像content
一样,你也可以使用无名插槽 .这是Polymer's 2.0 migration guide的示例
Here's关于github的讨论之一讨论提议使用插槽内容而只是列出插槽内容的一些优点
虽然它对内容的缺点也很少,但至少目前供应商已经同意插槽是前进的方向 .