是否可以自动或以编程方式插入特定类型的嵌套 Web 组件或元素,而无需指定slot
属性在他们身上?
考虑这样的结构:
<parent-element>
<child-element>Child 1</child-element>
<child-element>Child 2</child-element>
<p>Content</p>
</parent-element>
随着<parent-element>
有一个像这样的 Shadow DOM:
<div id="child-elements">
<slot name="child-elements">
<child-element>Default child</child-element>
</slot>
</div>
<div id="content">
<slot></slot>
</div>
预期结果是:
<parent-element>
<#shadow-root>
<div id="child-elements">
<slot name="child-elements">
<child-element>Child 1</child-element>
<child-element>Child 2</child-element>
</slot>
</div>
<div id="content">
<slot>
<p>Content</p>
</slot>
</div>
</parent-element>
换句话说,我想强制执行这一点<child-element>
s 只允许在<parent-element>
如同<td>
元素只允许在<tr>
元素。我希望它们被放置在<slot name="child-elements">
元素。必须指定一个slot
每个属性上的属性将它们放置在特定的插槽中<parent-element>
似乎多余。
同时,内的其余内容<parent-element>
应自动插入第二个<slot>
元素。
不过,我首先寻找一种在注册父元素时定义它的方法CustomElementRegistry.define() https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define目前仅支持extends
作为选项。
然后我想,也许有一个功能允许手动插入元素,即类似的东西childElement.slot('child-elements')
,但这似乎并不存在。
然后,我尝试在父元素的构造函数中以编程方式实现此目的,如下所示:
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
const childElements = this.getElementsByTagName('child-element');
const childElementSlot = this.shadowRoot.querySelector('[name="child-elements"]');
for (let i = 0; i < childElements.length; i++) {
childElementSlot.appendChild(childElements[i]);
}
}
虽然这不会将子元素移动到<slot name="child-elements">
,所以他们仍然被安排在第二个位置<slot>
元素。