Web Components 是浏览器原生支持的可复用自定义元素标准,核心包括 Custom Elements(通过 customElements.define() 注册含短横线的标签)、Shadow dom(用 attachShadow 封装样式与结构,避免全局污染)和 html Templates(用 template 元素提升结构清晰度与复用性)。

Web Components 是浏览器原生支持的一套技术标准,用来创建可复用、封装良好的自定义 HTML 元素。它不依赖框架,直接运行在 DOM 层,核心包括 Custom Elements、Shadow DOM 和 HTML Templates 三部分。其中 Custom Elements 是实现自定义标签(比如
Custom Elements:定义自己的 HTML 标签
通过 customElements.define() 注册一个新元素,必须继承 HTMLElement 或其子类(如 HTMLButtonElement),且标签名中必须包含短横线(-),例如 my-slider、data-table。
- 不能用纯字母或数字开头,也不能是单个单词(如 mybutton 会报错)
- 构造函数里不能调用 super() 之后再操作 this,需在 super() 后立即初始化,且不能访问 this.shadowRoot(此时还未挂载)
- 生命周期钩子有 connectedCallback(插入 DOM 时)、disconnectedCallback(移出时)、attributeChangedCallback(属性变化时)等
用 Shadow DOM 封装样式和结构
在 connectedCallback 中调用 this.attachShadow({ mode: ‘open’ }) 创建影子根节点,之后所有子节点和样式都作用于这个封闭环境,不会被外部 css 影响,也不会影响外部。
- mode: ‘open’ 表示可通过 this.shadowRoot 访问;’closed’ 则无法从外部获取 shadowRoot
- 可在 shadowRoot 中 innerHTML 插入模板,或用 appendChild 添加元素
- 支持
结合 HTML Template 提升可读性与复用性
把组件结构写在 标签里,用 document.getElementById 或 querySelector 获取后克隆使用,比拼接字符串更清晰安全。
立即学习“Java免费学习笔记(深入)”;
- template 内容默认不渲染,适合存放未激活的 ui 片段
- 克隆时用 template.content.clonenode(true),避免重复引用同一节点
- 可配合 slot 实现内容分发,让使用者传入自定义内容到指定位置
一个完整示例:带文本和点击反馈的按钮组件
下面是一个最小可行的自定义按钮:
class MyButton extends HTMLElement { constructor() { super(); const shadow = this.attachShadow({ mode: 'open' }); const template = document.createElement('template'); template.innerHTML = ` <style> button { background: #007bff; color: white; border: none; padding: 8px 16px; } button:hover { opacity: 0.8; } </style> <button><slot>Click me</slot></button> `; shadow.appendChild(template.content.cloneNode(true)); } connectedCallback() { this.shadowRoot.querySelector('button').addEventListener('click', () => { this.dispatchEvent(new CustomEvent('my-click', { detail: { label: this.textContent || 'default' } })); }); } } customElements.define('my-button', MyButton);
使用方式: