我有一个 Web 组件,它应该接受任意元素来包装其内容。虽然我可以在 Chrome 开发工具中看到插槽已正确分配,但 DOM 中什么也没有出现。以前有人见过这个问题吗?
定义
class ExampleParent extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = `
<slot name="as">
<slot name="prefix"></slot>
<slot></slot>
</slot>
`;
}
}
customElements.define('example-parent', ExampleParent);
祈求
<example-parent
style="
min-width: 100px;
height: 40px;
border: 1px solid red;
display: inline-block;
"
>
<button slot="as"></button>
<div slot="prefix">Prefix slot</div>
Default
</example-parent>
实际结果
预期结果
源代码
https://stackblitz.com/edit/nested-slots-ahtfyf?file=index.html https://stackblitz.com/edit/nested-slots-ahtfyf?file=index.html
你不能嵌套<slot>
元素kinda就像你不能嵌套一样<li>
元素。
所以喜欢与<li>
在哪里添加额外的<ul>
容器,
你必须添加一个额外的 Web 组件传递槽位内容:
update: added exportparts
and part
展示如何globalCSS 样式nestedShadowDOM JSWC
class MyCoolBaseClass extends HTMLElement {
constructor( html ) {
let style = "<style>:host{display:inline-block;background:pink}</style>";
super().attachShadow({mode:'open'}).innerHTML = style + html;
}
}
customElements.define('el-one', class extends MyCoolBaseClass {
constructor() {
super(`<el-two exportparts="title"><slot name="ONE" slot="TWO"></slot></el-two>`);
}
});
customElements.define('el-two', class extends MyCoolBaseClass {
constructor() {
super(`Hello <slot name="TWO"></slot> <b part="title">Web Components</b>`);
}
});
el-one { display:block; font-size:21px }
el-one::part(title){ color:green }
<el-one><b slot="ONE">Fantastic!</b></el-one>
<el-one><b slot="ONE">Great!</b></el-one>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)