如何将选项标签作为分布式节点传递给自定义元素(又名 <slot></slot>)

How to pass option tags to a custom element as distributed nodes (aka <slot></slot>)

我有一个这样定义的 Web 组件自定义元素。

 <template id="dropdown-template">
        <select>
            <slot></slot>
        </select>
    </template>
    <script>
        class Dropdown extends HTMLElement {
            constructor() {
                super();
                const shadowRoot = this.attachShadow({mode: 'open'});
                let template = document.getElementById('dropdown-template');
                shadowRoot.appendChild(template.content.cloneNode(true));
            }
        }
        customElements.define("drop-down", Dropdown);
    </script>

尝试使用它时,我尝试将带有值的选项标签传递到自定义元素中。

<drop-down>
     <option>one</option>
     <option>two</option>
     <option>three</option>
</drop-down>

这行不通。 select 元素显示有一个 <slot> 元素作为其直接子元素,并且它不呈现选项。这不可能与 <select> 标签有关吗?

不可能那样做,因为 <option> 标签的父元素必须是 <select> 标签。所以你可以使用 Shadow DOM 因为 <slot> 元素会破坏 parent/child 层次结构。

解决方案 1:移动元素

解决方法是将灯光 DOM 的内容移动到模板的 <select> 元素内。

class Dropdown extends HTMLElement {
    constructor() {
        super()
        const shadowRoot = this.attachShadow( {mode: 'open'} )
        let template = document.getElementById( 'dropdown-template' )
        shadowRoot.appendChild( template.content.cloneNode(true) )

        const select = shadowRoot.querySelector( 'select' )     
        shadowRoot.addEventListener( 'slotchange', ev => {      
            let node = this.querySelector( 'option' )
            node && select.append( node )
        } )
    }
}
customElements.define("drop-down", Dropdown);
<template id="dropdown-template">
    <select></select>
    <slot></slot>
</template>

<drop-down>
    <option>one</option>
    <option>two</option>
    <option>three</option>
</drop-down>

方案二:自定义<select>

另一种可能性是避免阴影 DOM 并将您的 drop-down 列表定义为自定义的 built-in <select> 元素。如果您想自定义布局,这可能不符合您的需求。

<select is="drop-down">
    <option>one</option>
    <option>two</option>
    <option>tree</option>
</select>