使用 Web Components 的完整指南

Web Components,HTML,原生前端


🌐 在 HTML 页面中使用 Web Components 的完整指南

Web Components 是一组浏览器原生 API,让你无需任何第三方库,就能创建可复用、封装良好的自定义 HTML 标签。它们可以直接在普通的 .html 文件中运行,兼容所有现代浏览器。


🧱 三大核心技术概览

| 技术 | 作用 | |------|------| | Custom Elements | 定义新标签(如 <my-button>)并绑定 JavaScript 逻辑 | | Shadow DOM | 隔离样式和 DOM,防止组件内外互相干扰 | | HTML Templates | 通过 <template> 定义可复用的结构,按需实例化 |

这三者结合,就能像搭积木一样构建页面。


📄 在 HTML 中直接使用 Web Components

你只需要两步:

  1. <script> 中定义并注册组件。
  2. 在 HTML 中使用该标签。

示例:创建一个 <counter-button>

下面是一个完整的 HTML 文件,包含从定义到使用的全部代码。

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>Web Components 示例</title>
</head>
<body>

  <!-- 使用自定义组件 -->
  <counter-button></counter-button>
  <counter-button style="--button-bg: #f43f5e;"></counter-button>

  <script>
    // 定义组件
    class CounterButton extends HTMLElement {
      constructor() {
        super();
        const shadow = this.attachShadow({ mode: 'open' });

        const button = document.createElement('button');
        const span = document.createElement('span');
        let count = 0;
        span.textContent = count;

        button.addEventListener('click', () => {
          count++;
          span.textContent = count;
          this.dispatchEvent(new CustomEvent('count-changed', { detail: { count } }));
        });

        const style = document.createElement('style');
        style.textContent = `
          button {
            padding: 10px 20px;
            font-size: 1rem;
            border: none;
            border-radius: 6px;
            background-color: var(--button-bg, #6366f1);
            color: var(--button-color, white);
            cursor: pointer;
          }
          button:hover { filter: brightness(0.9); }
          span { margin-left: 12px; font-weight: bold; }
        `;

        shadow.appendChild(style);
        shadow.appendChild(button);
        shadow.appendChild(span);
      }
    }
    customElements.define('counter-button', CounterButton);
  </script>

</body>
</html>

直接保存为 .html 文件,用浏览器打开即可看到两个可点击的计数器按钮。 🎨 通过 CSS 变量定制样式 组件内部使用了 var(--button-bg, #6366f1),允许外部通过 CSS 自定义属性覆盖样式。

<counter-button style="--button-bg: #10b981; --button-color: #fff;"></counter-button>

你可以像这样为不同实例赋予不同主题,而不影响其他组件。

📡 监听组件事件 组件每次点击都会派发 count-changed 事件,你可以用原生 JavaScript 监听:

<counter-button id="myCounter"></counter-button>
<script>
  document.getElementById('myCounter').addEventListener('count-changed', (e) => {
    console.log('当前计数:', e.detail.count);
  });
</script>

🧩 复用与维护 将组件定义放在单独的 .js 文件中,然后在多个页面引用:

<script src="counter-button.js"></script>

这样就能在所有 HTML 页面中共享同一个组件。

🚀 为什么选择原生 Web Components? 零依赖:无需 npm、构建工具或框架。

原生支持:Chrome、Firefox、Safari、Edge 均已稳定支持。

真正封装:Shadow DOM 保证样式隔离,不怕全局污染。

未来兼容:基于标准,不会因框架更替而失效。