Web组件:传递要显示的数据时的插槽与属性

问题描述 投票:0回答:1

将数据(其目的是在 Shadow DOM 中显示)传递到自定义元素的更好方法是什么。这是通过使用属性还是插槽?

属性示例

class MyAttributeComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({
      mode: "open"
    });
  }

  connectedCallback() {
    const heading = this.getAttribute("heading");

    this.shadowRoot.innerHTML = `
            <h2>${heading}</h2>
          `;
  }
}
customElements.define("my-attribute-component", MyAttributeComponent);
<my-attribute-component heading="this is my attribute heading"></my-attribute-component>

老虎机示例

class MySlotComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({
      mode: "open"
    });

    this.shadowRoot.innerHTML = `
            <slot></slot>
          `;
  }
}
customElements.define("my-slot-component", MySlotComponent);
<my-slot-component>
  <h2>this is my slotted heading</h2>
</my-slot-component>

javascript html shadow-dom custom-element
1个回答
0
投票

没有“更好”他们都做不同的事情。

customElements.define("my-component", class extends HTMLElement {
  constructor() {
    super()
      .attachShadow({mode:"open"})
      .innerHTML =
      `<style>h1 {border: 5px solid blue} `+
      `*::slotted(h1){ background:pink }`+
      `</style>` +
      `<slot name="title"></slot>` +
      `<h1></h1>`;
  }
  connectedCallback() {
    this.shadowRoot.querySelector("h1").innerHTML = this.getAttribute("subtitle");
  }
});
<style>
  h1 {
    border: 5px solid green
  }
</style>
<my-component subtitle="Web Component World!">
  <h1 slot="title">Hello,</h1>
</my-component>

© www.soinside.com 2019 - 2024. All rights reserved.