HTML5 Web Components 通过 Custom Elements、Shadow DOM 和 HTML 模板实现原生组件化开发,支持自定义标签、样式隔离、模板复用与属性响应,适用于轻量级项目和跨框架组件共享。

HTML5 Web Components 是一套可以让开发者创建可复用、封装良好的自定义 HTML 元素的技术。它不依赖任何框架,原生支持现代浏览器,适合构建组件化前端应用。核心由三项技术组成:自定义元素(Custom Elements)、影子 DOM(Shadow DOM)和 HTML 模板()。下面介绍如何使用它们实现组件化开发。
1. 使用 Custom Elements 定义自定义标签
Custom Elements 允许你定义自己的 HTML 标签,并绑定 JavaScript 类来控制其行为。
通过 customElements.define() 方法注册一个新元素,例如创建一个
class MyCard extends HTMLElement {
constructor() {
super();
this.innerHTML = `
${this.getAttribute('title')}
${this.textContent}
立即学习“前端免费学习笔记(深入)”;
`;
}
}
customElements.define('my-card', MyCard);
之后就可以在页面中使用:
2. 利用 Shadow DOM 实现样式与结构隔离
Shadow DOM 能将组件的 DOM 和 CSS 封装起来,避免全局污染。在构造函数中调用 attachShadow() 创建影子根节点。
修改上面的例子,加入 Shadow DOM:
class MyCard extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
const title = this.getAttribute('title');
const content = this.textContent;
shadow.innerHTML = `
${title}
${content}
`;
}
}
customElements.define('my-card', MyCard);
:host 是 Shadow DOM 中的关键选择器,用于选中组件本身。
mallcloud商城基于SpringBoot2.x、SpringCloud和SpringCloudAlibaba并采用前后端分离vue的企业级微服务敏捷开发系统架构。并引入组件化的思想实现高内聚低耦合,项目代码简洁注释丰富上手容易,适合学习和企业中使用。真正实现了基于RBAC、jwt和oauth2的无状态统一权限认证的解决方案,面向互联网设计同时适合B端和C端用户,支持CI/CD多环境部署,并提
3. 使用 提前定义组件模板
对于结构较复杂的组件,建议使用 标签预定义 HTML 模板,提升性能和可维护性。
在 HTML 中定义模板:
默认标题
默认内容
JavaScript 中使用模板实例化:
class MyCard extends HTMLElement {
constructor() {
super();
const template = document.getElementById('card-template');
const content = template.content.cloneNode(true);
this.attachShadow({ mode: 'open' }).appendChild(content);
}
}
customElements.define('my-card', MyCard);
配合
4. 支持属性监听与状态更新
通过定义 observedAttributes 和 attributeChangedCallback,可以监听属性变化并响应更新。
class MyCard extends HTMLElement {
static get observedAttributes() {
return ['title', 'theme'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'title' && this.shadowRoot) {
const h3 = this.shadowRoot.querySelector('h3');
if (h3) h3.textContent = newValue;
}
if (name === 'theme') {
this.shadowRoot.host.style.backgroundColor = newValue === 'dark' ? '#333' : '#fff';
}
}
}
这样当外部修改属性时,组件能自动更新界面。
基本上就这些。HTML5 Web Components 提供了原生的组件化能力,无需引入框架即可实现高内聚、低耦合的 UI 模块。虽然生态不如 React 或 Vue 丰富,但在轻量级项目、设计系统或跨框架组件共享中非常实用。关键是理解 Custom Elements、Shadow DOM 和 的协作方式,就能写出干净可复用的组件。










