如何将选项标签作为分布式节点传递给自定义元素(又名 <slot></slot>) [英] How to pass option tags to a custom element as distributed nodes (aka <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 元素显示有一个
元素作为其直接子元素,并且它不呈现选项.这不能用 标签实现吗?
This doesn't work. The select element is shown to have a <slot>
element as its direct child, and it doesn't render the options. Is this not possible to do with the <select>
tag?
推荐答案
不可能那样做,因为 标签的父元素必须是
<选择>
标签.所以你可以使用 Shadow DOM,因为
元素会破坏父/子层次结构.
It not possible to do it like that because the parent element of an <option>
tag must be a <select>
tag. So you can use with Shadow DOM because the <slot>
element will break the parent/child hierachy.
方案一:移动元素
一种解决方法是将光 DOM 的内容移动到模板中的 元素内.
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>
方案二:自定义
另一种可能性是避免使用 Shadow DOM 并将下拉列表定义为自定义的内置 元素.如果您想自定义布局,这可能不符合您的需求.
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>
这篇关于如何将选项标签作为分布式节点传递给自定义元素(又名 <slot></slot>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!