我有一个 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
最佳答案
您不能嵌套 <slot>
元素有点就像你不能嵌套<li>
元素。
就像<li>
一样在其中添加额外的 <ul>
容器,
您必须添加一个额外的 Web 组件来传递插槽内容:
更新:添加exportparts
和part
展示如何全局 CSS 样式嵌套 ShadowDOM 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>
关于javascript - Web组件中嵌套槽的内容不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73732956/