Web Components:原生组件化开发新趋势
开篇:什么是 Web Components?

想象一下,你想用乐高积木搭建一个房子。每一块积木都独立存在,你可以自由地组合、拆卸和重用它们。Web Components 就是网页世界的“乐高积木”,它让你把网页的不同部分封装成可复用、独立的组件。
简单来说,Web Components 是一组浏览器原生支持的技术,允许你创建自己的 HTML 标签,并给这些标签添加样式和行为。
比如,你可以定义一个 <my-button> 按钮标签,在多个项目中使用它而不必每次都写重复的代码。这不仅节省时间,还使代码更容易维护和阅读。
环境准备:开始之前你需要什么?

好消息是:不需要安装复杂的开发工具!你只需要:
- 文本编辑器(推荐 VS Code)
- 现代浏览器(如 Chrome、Edge 或 Firefox)
第一步:创建你的第一个 HTML 文件
新建一个文件夹,命名为 web-components-demo,然后在里面创建一个名为 index.html 的文件,内容如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>我的第一个 Web Component</title>
</head>
<body>
<h1>Hello, Web Components!</h1>
<script type="module" src="components/my-button.js"></script>
</body>
</html>
第二步:创建组件文件
在 components 目录下创建 my-button.js 文件:
class MyButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
const button = document.createElement('button');
button.textContent = '点击我';
button.style.padding = '10px 20px';
button.style.backgroundColor = '#4CAF50';
button.style.color = 'white';
button.style.border = 'none';
button.style.borderRadius = '4px';
button.addEventListener('click', () => {
alert('按钮被点击了!');
});
this.shadowRoot.appendChild(button);
}
}
customElements.define('my-button', MyButton);
现在,打开浏览器访问这个页面,你应该能看到一个绿色按钮。
核心概念:组成 Web Components 的三大支柱

Web Components 的核心技术由三个核心 API 组成,分别是:
1. 自定义元素(Custom Elements)
这是 Web Components 的核心功能之一,允许我们定义新的 HTML 元素。
语法:
class MyElement extends HTMLElement {
constructor() {
super();
// 初始化逻辑
}
}
customElements.define('my-element', MyElement);
这样你就可以在 HTML 中使用 <my-element> 这样的自定义标签。
2. Shadow DOM(影子 DOM)
Shadow DOM 提供了一个与主文档分离的独立 DOM 树,这意味着你在组件里写的样式和结构不会影响到其他地方的内容。
基本用法:
this.attachShadow({ mode: 'open' });
const div = document.createElement('div');
div.textContent = '我在 Shadow DOM 中';
this.shadowRoot.appendChild(div);
你可以将样式、HTML 都放在 shadowRoot 中,实现完全隔离。
3. HTML 模板(Template & Slot)
为了让组件更灵活、可复用,我们可以使用 <template> 和 <slot>。
使用模板 <template>
<template id="my-template">
<style>
p { color: blue; }
</style>
<p>这是一个模板中的段落。</p>
</template>
在组件中引用模板
connectedCallback() {
const template = document.getElementById('my-template');
const content = template.content.cloneNode(true);
this.shadowRoot.appendChild(content);
}
插槽 <slot> 实现内容插入
<!-- 组件内部 -->
<slot name="title">默认标题</slot>
<!-- 使用组件时 -->
<my-card>
<span slot="title">我的卡片标题</span>
</my-card>
实战项目:构建一个带插槽的可交互按钮组件

我们现在来做一个完整的实战项目——一个可以定制文字、样式的按钮组件 <interactive-button>,并支持插槽。
第一步:修改 HTML 结构
更新 index.html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>互动按钮组件</title>
</head>
<body>
<h1>欢迎使用互动按钮</h1>
<interactive-button color="#f44336">点击试试看</interactive-button>
<script type="module" src="components/interactive-button.js"></script>
</body>
</html>
第二步:创建组件逻辑
创建 components/interactive-button.js:
class InteractiveButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
// 获取属性值
const color = this.getAttribute('color') || '#2196F3';
// 创建样式
const style = document.createElement('style');
style.textContent = `
button {
padding: 10px 20px;
background-color: ${color};
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
opacity: 0.9;
}
`;
// 创建按钮元素
const button = document.createElement('button');
button.textContent = this.textContent.trim(); // 获取插槽内容
// 添加点击事件
button.addEventListener('click', () => {
alert(`你点击了按钮:“${button.textContent}”`);
});
// 添加到 shadowRoot
this.shadowRoot.appendChild(style);
this.shadowRoot.appendChild(button);
}
}
customElements.define('interactive-button', InteractiveButton);
效果说明:
运行后你会看到一个红色按钮,上面写着“点击试试看”。点击会弹出提示框。
常见问题解答(FAQ)
Q1:为什么用了样式但是没生效?
A:因为 Web Components 中使用的是 Shadow DOM,默认样式不会穿透进来。请确保样式写在组件内或使用 CSS 变量传入。
Q2:如何让按钮里的文字动态改变?
A:可以通过 MutationObserver 观察节点变化,也可以提供 attribute 来控制内容,例如添加 text="新的文字"。
Q3:Web Components 能和其他框架一起使用吗?
A:当然可以!Web Components 是原生特性,可以在 React、Vue、Angular 中像普通 HTML 元素一样使用。
学习建议:接下来应该学什么?
恭喜你已经完成了第一个 Web Components 项目的搭建!
下一步你可以继续学习:
- ✅ 如何在组件之间通信(使用自定义事件)
- ✅ 如何通过 attributes 控制组件状态
- ✅ 引入第三方库(比如 Vue 或 Lit)来优化组件开发体验
- ✅ 使用模块系统(ES Modules)组织复杂项目结构
- ✅ 将组件打包发布到 npm,让别人也能使用你的组件
总结
本教程中,我们从零开始了解了 Web Components 的三大核心技术:自定义元素、Shadow DOM 和 HTML 模板;并通过实战项目创建了一个可复用的按钮组件。Web Components 的优势在于其无需依赖特定框架即可开发可复用 UI 组件,非常适合现代前端架构的发展趋势。
希望你能坚持练习,将这些基础掌握扎实,逐步构建出更加丰富强大的组件系统!
作者寄语:
“学编程就像搭积木,每一步都很小,但累积起来就能创造奇迹。” —— 愿你越学越轻松,越敲越自信!

评论 0