实现说明
真正干活的是类 TabHost,其余都是接线。
循环只出现在 for (const slot of root.querySelectorAll('slot')),它的每次迭代处理一个元素。
顶层就这几处状态:host、tab、panel。
使用要点
document只存在于浏览器——Node 运行时没有现成的垫片。
常见问题
「slotchange 感知插槽成员变化」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
核心语句
slot.addEventListener('slotchange', () => {
console.log(slot.name || 'default', 'slot has', slot.assignedElements().length, 'elements');
});
代码示例
// slotchange fires when nodes start or stop matching a slot; assignedElements()
// reports the current membership, so counters stay in sync with the light DOM.
class TabHost extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: 'open' });
root.innerHTML = '<slot name="tab"></slot><slot name="panel" hidden></slot>';
for (const slot of root.querySelectorAll('slot')) {
slot.addEventListener('slotchange', () => {
console.log(slot.name || 'default', 'slot has', slot.assignedElements().length, 'elements');
});
}
}
}
customElements.define('tab-host', TabHost);
const host = document.createElement('tab-host');
const tab = document.createElement('button');
tab.slot = 'tab'; // assigning the slot attribute moves the node into that slot
tab.textContent = 'Billing';
const panel = document.createElement('section');
panel.slot = 'panel';
panel.textContent = 'Invoices';
host.append(tab, panel);
document.body.append(host);