【问题标题】:Share the same shadow DOM between several shadow hosts?在多个影子主机之间共享同一个影子 DOM?
【发布时间】:2019-07-31 08:58:13
【问题描述】:

我只是在发现 Web 组件,我还不确定是否能很好地理解它。

但这是我的问题。似乎它有很多优点。 我想知道是否可以在多个影子主机上共享同一个影子 DOM?

我想要的是网页上某个元素的多个实例。
如果更新(单个)shadow DOM,所有实例也会自动更新。

它是影子 DOM 的用途之一吗?我怎样才能实现它?

谢谢!

【问题讨论】:

  • 没有。每个影子主机都拥有自己的影子 DOM。你需要复制 DOM 内容

标签: html web-component shadow-dom


【解决方案1】:

您可以通过让包含组件在属性更改时侦听事件并将值向下传递给子组件来实现相同的效果。这样您就不会共享 shadow DOM 实例本身,而是可以重复使用组件而无需任何代码重复。

class XContainer extends HTMLElement {
  constructor() {
    super();
    
    this.total = 0;
  }
  
  connectedCallback() {    
    this.addEventListener('x-increment', this.onIncrement);
    
    this.onIncrement = this.onIncrement.bind(this);
  }
  
  onIncrement(event) {
    this.total = this.total + event.detail.amount;
    
    this.querySelectorAll('x-counter').forEach((counterEl) => {
      counterEl.total = this.total;
    });
  }
}
customElements.define('x-container', XContainer);


class XControls extends HTMLElement {
  constructor() {
    super();
    
    this.attachShadow({ mode: 'open' });
    
    this.shadowRoot.innerHTML = `
      <button>+</button>
    `;
  }
    
  connectedCallback() {    
    this.shadowRoot.querySelector('button').addEventListener('click', this.onClick);
    
    this.onClick = this.onClick.bind(this);
  }
  
  onClick(event) {
    this.dispatchEvent(new CustomEvent('x-increment', {
      bubbles: true,
      composed: true,
      detail: {
        amount: 1,
      }
    }));
  }
}
customElements.define('x-controls', XControls);


class XCounter extends HTMLElement {
  constructor() {
    super();
  
    this.attachShadow({ mode: 'open' });
    
    this.shadowRoot.innerHTML = `
      <h2>Total: <span>0</span>
    `;
  }
  
  set total(value) {
    this.shadowRoot.querySelector('span').innerText = value;
  }
}
customElements.define('x-counter', XCounter);
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Web Component 101</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>  
  <body>

    <x-container>
      <x-counter></x-counter>
      <hr>
      <x-counter></x-counter>
      <hr>
      <x-controls></x-controls>
    </x-container>
    
  </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2015-03-03
    • 1970-01-01
    相关资源
    最近更新 更多