Web组件嵌套插槽

时间:2018-02-17 14:31:58

标签: web-component shadow-dom custom-element native-web-component

有没有更好的方法将插槽传递给深层嵌套的组件?

的index.html

  <outer-comp>
    <span slot=foo>Lorem ipsum</span>
  </outer-comp>

外部组件:

  <inner-comp>
    <slot name=foo slot=foo></slot>
  </inner-comp>

内部组件:

  <slot name=foo></slot>

1 个答案:

答案 0 :(得分:3)

这很好用:):

&#13;
&#13;
class ElOuter extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }
  
  connectedCallback() {
    this.shadowRoot.innerHTML = `
      <p>- outer start</p>
      <el-inner>
        <slot name="heading" slot="header"></slot>
      </el-inner>
      <slot></slot>
      <p>- outer stop</p>
    `;
  }
}
customElements.define('el-outer', ElOuter);

class ElInner extends ElOuter {
  connectedCallback() {
    this.shadowRoot.innerHTML = `
      <p>-- inner start</p>
      <slot name="header"></slot>
      <p>-- inner stop</p>
    `;
  }
}
customElements.define('el-inner', ElInner);
&#13;
<el-outer>
  <h2 slot="heading">hey</h2>
  <p>I will be in the default content</p>
</el-outer>
&#13;
&#13;
&#13;