1

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

索引.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>
4

1 回答 1

7

这工作得很好:)

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);
<el-outer>
  <h2 slot="heading">hey</h2>
  <p>I will be in the default content</p>
</el-outer>

于 2018-02-22T08:07:07.333 回答