Web Components 基础入门


Web Components 基础入门

Web Components 是一套 Web 标准,让开发者能够创建可复用的自定义 HTML 元素。

什么是 Web Components

Web Components 由三个主要技术组成:

  • Custom Elements - 定义自定义元素及其行为
  • Shadow DOM - 封装样式和结构
  • HTML Templates - 声明式模板

创建自定义元素

基本语法

// 定义自定义元素
class MyComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    this.shadowRoot.innerHTML = `
      <style>
        :host { display: block; padding: 10px; }
      </style>
      <p>Hello Web Components!</p>
    `;
  }
}

// 注册元素
customElements.define('my-component', MyComponent);

使用自定义元素

<my-component></my-component>

Shadow DOM

Shadow DOM 提供样式封装:

class ShadowComponent extends HTMLElement {
  connectedCallback() {
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.innerHTML = `
      <style>
        p { color: red; }
      </style>
      <p>这段文字是红色的</p>
    `;
  }
}

生命周期回调

  • connectedCallback() - 元素插入 DOM 时调用
  • disconnectedCallback() - 元素从 DOM 移除时调用
  • attributeChangedCallback() - 属性变化时调用

使用 HTML Templates

<template id="my-template">
  <style>
    .container { border: 1px solid #ccc; padding: 10px; }
  </style>
  <div class="container">
    <slot></slot>
  </div>
</template>

<script>
  class TemplateComponent extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: 'open' });
      const template = document.getElementById('my-template');
      this.shadowRoot.appendChild(template.content.cloneNode(true));
    }
  }
  customElements.define('template-component', TemplateComponent);
</script>

属性和属性

class PropsComponent extends HTMLElement {
  static get observedAttributes() {
    return ['name', 'count'];
  }

  get name() {
    return this.getAttribute('name') || 'default';
  }

  set name(value) {
    this.setAttribute('name', value);
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (name === 'name') {
      this.render();
    }
  }
}

总结

Web Components 让我们能够:

  • 创建可复用的自定义元素
  • 封装样式和实现
  • 跨框架使用组件

更多详情请参考 MDN Web Components