我有一个Web组件,它应该接受任意元素来包装其内容.虽然我可以在Chrome Dev工具中看到插槽分配正确,但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>个元素kinda,就像你不能有嵌套的<li>个元素一样.

So like with <li> where you add an extra <ul> container,
you have to add an extra Web Component which passes on slot content:

<script>
class MyCoolBaseClass extends HTMLElement {
  constructor(html) {
    super().attachShadow({mode:'open'}).innerHTML = html;
  }
}
customElements.define('el-one', class extends MyCoolBaseClass {
  constructor() {
    super(`<el-two><slot   name="ONE" slot="TWO"   ></slot></el-two>`);
  }
});
</script>

<el-one>
  <b slot="ONE">Fantastic!</b>
</el-one>

<script>
customElements.define('el-two', class extends MyCoolBaseClass {
  constructor() {
    super(`Hello <slot   name="TWO"   ></slot> Web Components`);
  }
});
</script>

Javascript相关问答推荐

我可以后增量超过1(最好是内联)吗?

创建私有JS出口

React对话框模式在用户单击预期按钮之前出现

如何保持子画布元素的1:1宽高比?

创建1:1比例元素,以另一个元素为中心

在JavaScript中检索一些文本

React:未调用useState变量在调试器的事件处理程序中不可用

将json数组项转换为js中的扁平

单击更新页面的按钮后,页面刷新;测试/断言超时,有两个标题,但没有一个标题

Redux工具包查询(RTKQ)端点无效并重新验证多次触发

从PWA中的内部存储读取文件

Redux查询多个数据库Api reducerPath&

如何在mongoose中链接两个模型?

处理时间和字符串时MySQL表中显示的日期无效

Chart.js-显示值应该在其中的引用区域

VUE 3捕获错误并呈现另一个组件

单个HTML中的多个HTML文件

如何在.NET Core中将chtml文件链接到Java脚本文件?

在单击按钮时生成多个表单时的处理状态

连续添加promise 时,如何在所有promise 都已结算时解除加载覆盖