javascript - Web组件中嵌套槽的内容不可见

标签 javascript web-component lit

我有一个 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>

实际结果

enter image description here

预期结果

enter image description here

源代码

https://stackblitz.com/edit/nested-slots-ahtfyf?file=index.html

最佳答案

您不能嵌套 <slot>元素有点就像你不能嵌套<li>元素。

就像<li>一样在其中添加额外的 <ul>容器,
您必须添加一个额外的 Web 组件来传递插槽内容:

更新:添加exportpartspart展示如何全局 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/

相关文章:

typescript - Typescript 用户定义类型/对象的数组作为 Lit v2 中的属性

javascript - 如何在 angular-ui-grid 上自定义导出网格菜单?

javascript - 如何在asp mvc中获取列表的复选框值

javascript - 忽略本地 url 的 html 中的基本 url

css - 如何防止外部 CSS 覆盖 Web 组件样式

node.js - 能够使用 Polymer 3 解析模块,但不能使用 Lit Element

javascript - 如何将部分 View 中生成的 HTML 插入到 javascript 代码中?

recaptcha - 自定义元素 Web 组件影子 DOM 供应商脚本/元素

html - 如何在元素内容中访问模板的innerHTML

vaadin - 在点亮元素中使用 Vaadin 徽章