如何将选项标签作为分布式节点传递给自定义元素(又名 <slot></slot>) [英] How to pass option tags to a custom element as distributed nodes (aka <slot></slot>)

查看:227
本文介绍了如何将选项标签作为分布式节点传递给自定义元素(又名 <slot></slot>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a web component custom element defined like so.

 <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>

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

When trying to use it, I try and pass option tags with values into the custom element.

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

这不起作用.select 元素显示有一个 元素作为其直接子元素,并且它不呈现选项.这不能用 元素内.

A workaround is to move the content of the light DOM inside the <select> element in the template.

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>

方案二:自定义 元素.如果您想自定义布局,这可能不符合您的需求.

Another possibility is to avoid Shadow DOM and define your drop-down list as a customized built-in <select> element. Maybe this won't fit your needs if you want to customize the layout.

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

这篇关于如何将选项标签作为分布式节点传递给自定义元素(又名 &lt;slot&gt;&lt;/slot&gt;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆