Componentes Web

Componentes Web são um conjunto de normas atualmente sendo produzidos por engenheiros do Google como também uma especificação da W3C que permitem a criação de componentes reutilizáveis em documentos e aplicações web. A intenção por trás deles é trazer a engenharia de software baseada em componentes para a Web. O modelo de componentes permite encapsulamento e interoperabilidade de elementos HTML individuais.

O suporte para os componentes web está presente nos principais navegadores web, com polyfills disponíveis para os demais sem suporte.[1]

Componentes Web consistem em 4 elementos principais que podem ser utilizados em conjunto ou separadamente:

  • Elementos personalizados
  • Sombra do DOM
  • Importação de HTML
  • Modelos HTML

Exemplo

A definição do componente:

export class MyCounter extends HTMLElement {
  #count;
  #span;
  #button;

  connectedCallback() {
    const start = Number(this.getAttribute('start'));
    this.#count = Math.max(0, start || 5);

    // Se não possuir Declarative Shadow Root
    if (!this.shadowRoot) {
      this.attachShadow({ mode: 'open' }).innerHTML = `
        <style>
          :host {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            height: 100vh;
          }
          .label {
            font: 1.125rem Noto, sans-serif;
          }
        </style>
        <span class="label"></span>
        <button>Contar</button>
      `;
    }
    this.#span = this.shadowRoot.querySelector('.label');
    this.#button = this.shadowRoot.querySelector('button');
    this.#button.addEventListener('click', this.decrement.bind(this));
    this.requestUpdate();
  }

  requestUpdate() {
    this.#span.textContent = this.label;
    this.#button.disabled = this.#count === 0;
  }

  get label() {
    switch (this.#count) {
      case 0: return `Fim.`;
      case 1: return `Encerra no próximo clique!`;
      default: return `Encerra em ${this.#count} cliques.`;
    }
  }

  decrement() {
    if (this.#count > 0) {
      this.#count--;
    }
    this.requestUpdate();
  }
}
customElements.define('my-counter', MyCounter);

E o uso:

<my-counter start="5"></my-counter>

Ou com Declarative Shadow DOM (DSD) para uso com Server-Side Rendering (SSR):[2]

<my-counter start="5">
  <template shadowrootmode="open">
    <style>
      :host {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        height: 100vh;
      }
      .label {
        font: 1.125rem Noto, sans-serif;
      }
    </style>
    <span class="label">Encerra em 5 cliques.</span>
    <button>Contar</button>
  </template>
</my-counter>

Referências

  1. «webcomponents.org». www.webcomponents.org. Consultado em 14 de dezembro de 2023 
  2. Miller, Jason; Freed, Mason (17 de fevereiro de 2024). «Declarative Shadow DOM». developer.chrome.com (em inglês). Consultado em 2 de março de 2024 

Ligações externas

Ícone de esboço Este artigo sobre programação de computadores é um esboço. Você pode ajudar a Wikipédia expandindo-o.

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.