如何构建一个与框架无关的组件系统(Web Components实践)?

使用Web Components可构建与框架无关的UI组件系统,通过Custom Elements定义标签、Shadow DOM实现样式隔离、HTML Templates提升可维护性,并结合属性监听与事件通信,使组件可在任意技术栈中复用,适用于设计系统与微前端场景。

如何构建一个与框架无关的组件系统(Web Components实践)?

构建一个与框架无关的组件系统,关键在于使用原生 Web 技术实现可复用、可封装、可互操作的 UI 组件。Web Components 正是为此而生——它是一组浏览器原生支持的 API,包括自定义元素(Custom Elements)、影子 DOM(Shadow DOM)和 HTML 模板(HTML Templates)。通过它们,你可以创建完全独立、样式隔离、行为封装的组件,无论项目使用 React、Vue、Angular 还是纯 HTML,都能直接使用。

使用 Custom Elements 定义组件标签

Custom Elements 允许你注册新的 HTML 标签,并将其关联到一个 JavaScript 类。这是实现组件“可声明式调用”的基础。

定义一个简单的按钮组件:

class MyButton extends HTMLElement {
  connectedCallback() {
    if (this.innerHTML.trim() === ”) {
      this.innerHTML = ‘点击我’;
    }
    this.setAttribute(‘role’, ‘button’);
    this.tabIndex = 0;
  }
}

customElements.define(‘my-button’, MyButton);

之后在任意页面中都可以使用 <my-button></my-button>,无需任何框架支持。

用 Shadow DOM 实现样式和结构隔离

直接操作 innerHTML 容易导致样式冲突和逻辑泄露。使用 Shadow DOM 可以将组件内部的 DOM 和 CSS 与外部页面隔离开。

改进上面的按钮,加入 Shadow DOM:

class MyButton extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: ‘open’ });
  }

  connectedCallback() {
    const label = this.getAttribute(‘label’) || ‘点击我’;
    this.shadowRoot.innerHTML = `
      <style>
        button {
          padding: 8px 16px;
          border: none;
          background: #007bff;
          color: white;
          border-radius: 4px;
          cursor: pointer;
        }
      </style>
      <button>${label}</button>`;

    this.shadowRoot.querySelector(‘button’)
      .addEventListener(‘click’, () => {
        this.dispatchEvent(new CustomEvent(‘my-click’, { bubbles: true }));
      });
  }
}

customElements.define(‘my-button’, MyButton);

现在组件内部样式不会影响外部,外部样式也不会穿透进来,真正实现封装。

结合 HTML Templates 提高可维护性

把模板写在 JavaScript 字符串里不利于维护。可以使用 <template> 标签预定义结构。

在 HTML 中定义模板:

如何构建一个与框架无关的组件系统(Web Components实践)?

ViiTor实时翻译

AI实时多语言翻译专家!强大的语音识别、AR翻译功能。

如何构建一个与框架无关的组件系统(Web Components实践)?116

查看详情 如何构建一个与框架无关的组件系统(Web Components实践)?

<template id=”my-button-template”>
  <style>
    button { padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; }
  </style>
  <button><slot>点击我</slot></button>
</template>

组件类中引用模板:

const template = document.getElementById(‘my-button-template’).content;

class MyButton extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: ‘open’ });
    this.shadowRoot.appendChild(template.cloneNode(true));
  }

  connectedCallback() {
    const button = this.shadowRoot.querySelector(‘button’);
    button.addEventListener(‘click’, () => {
      this.dispatchEvent(new CustomEvent(‘my-click’, { bubbles: true }));
    });
  }
}

customElements.define(‘my-button’, MyButton);

使用 <slot> 支持内容分发,让组件更灵活。

支持属性与事件通信

为了让组件更通用,需要响应属性变化并对外暴露事件。

监听属性变化:

static get observedAttributes() { return [‘label’, ‘disabled’]; }

attributeChangedCallback(name, oldValue, newValue) {
  if (name === ‘label’ && oldValue !== newValue) {
    const button = this.shadowRoot.querySelector(‘button’);
    if (button) button.textContent = newValue;
  }
  if (name === ‘disabled’) {
    const button = this.shadowRoot.querySelector(‘button’);
    button.disabled = this.hasAttribute(‘disabled’);
  }
}

在使用时:

<my-button label=”提交” disabled></my-button>

组件可通过 dispatchEvent 发送自定义事件,宿主环境用 addEventListener 监听,实现跨框架通信。

基本上就这些。通过 Custom Elements + Shadow DOM + HTML Templates 的组合,你可以构建出真正与框架无关、可嵌入任何技术的 UI 组件系统。只要浏览器支持,就能运行。适合设计系统、微前端、跨团队协作等场景。不复杂但容易忽略细节,比如事件冒泡、属性观察、slot 使用等,掌握后能大幅提升组件的通用性和健壮性。

css vue react javascript java html 前端 node 浏览器 app 事件冒泡 JavaScript css html angular Static define if 封装 const 字符串 class pointer 事件 constructor dom this innerHTML padding border background ui

上一篇
下一篇
text=ZqhQzanResources