Web Components:原生组件化开发新趋势(面向零基础初学者)
一、开篇:Web Components 是什么?

想象一下,你想盖一座房子,但每一块砖都要自己造,非常麻烦。如果有一种工具,可以帮你直接“拼积木”一样地搭建网页,那就方便多了。Web Components 就是这种“积木式”的网页构建方式。
它不是框架(比如 Vue 或 React),而是浏览器本身支持的一种原生技术。通过 Web Components,你可以:
- 自定义 HTML 标签(例如
<my-header>) - 把样式和结构封装起来,防止互相干扰
- 在不同项目中重复使用这些自定义组件
这就像你设计了一块独特的砖头,可以在所有建筑项目中随意使用!
二、环境准备:我们需要哪些工具?

学习 Web Components 不需要复杂的环境,我们只需要:
1. 一个浏览器
推荐使用:
- Chrome(推荐开发者工具)
- Firefox 或 Edge(均可)
2. 一个代码编辑器
推荐:
- VS Code(免费,功能强大) 下载地址:https://code.visualstudio.com/
3. 本地运行环境(可选,便于调试)
方法一:直接用浏览器打开 .html 文件
你只需新建一个 index.html 文件,双击打开即可。
方法二:启动本地服务器(更推荐)
这样可以避免浏览器的安全限制,适合后续开发。
在终端或命令行输入以下命令(需先安装 Node.js):
npx http-server
没有安装 Node.js?先去官网下载安装:https://nodejs.org/
三、核心概念:什么是 Web Components?
Web Components 由三项核心技术组成:
| 技术名称 | 功能说明 |
|---|---|
| Custom Elements | 创建新的 HTML 元素(如 <my-button>) |
| Shadow DOM | 把组件的 HTML 和 CSS 隔离出来,不被外部影响 |
| HTML Templates | 存放不会立刻显示的内容,用于动态创建组件 |
下面我们将逐一介绍它们,并给出示例。
1. Custom Elements(自定义元素)
这是 Web Components 的核心:让你能写自己的 HTML 标签。
示例:定义一个自定义按钮 <custom-button>
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Custom Button</title>
<script type="module">
class CustomButton extends HTMLElement {
constructor() {
super();
this.innerHTML = `<button>这是一个自定义按钮</button>`;
}
}
customElements.define('custom-button', CustomButton);
</script>
</head>
<body>
<custom-button></custom-button>
</body>
</html>
📌 解释:
class CustomButton:定义组件类extends HTMLElement:表示这是个 HTML 元素customElements.define():注册组件为<custom-button>- 页面中可以直接使用这个标签了!
🎯 练习:请尝试定义一个 <custom-title> 组件,显示一个大标题 "欢迎来到我的网站!"
2. Shadow DOM(影子 DOM)
如果你希望你的组件样式不受到页面其他部分的影响,就可以用 Shadow DOM 来隔离作用域。
示例:给我们的按钮加上独立样式
<script type="module">
class CustomButton extends HTMLElement {
constructor() {
super();
// 创建 Shadow DOM
const shadow = this.attachShadow({ mode: 'open' });
// 创建按钮元素
const button = document.createElement('button');
button.textContent = '点我!';
// 创建样式
const style = document.createElement('style');
style.textContent = `
button {
background-color: #007bff;
color: white;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
}
`;
// 把内容和样式加到 shadow 中
shadow.appendChild(style);
shadow.appendChild(button);
}
}
customElements.define('custom-button', CustomButton);
</script>
📌 解释:
attachShadow():创建了一个独立的空间- 这里写的样式只会对当前组件生效,不会影响页面其它部分
🎯 练习:给按钮加一个 hover 变色效果,确保不影响全局按钮样式
3. HTML Templates(模板)
有时候你不希望组件一开始就显示出来,而是在特定时间再加载,可以用 <template> 标签来提前准备好内容。
示例:使用模板创建组件内容
<template id="my-template">
<style>
div {
background: #f0f0f0;
padding: 20px;
border-radius: 8px;
margin: 10px 0;
}
</style>
<div>
我是一个模板组件!
</div>
</template>
<script>
class TemplateComponent extends HTMLElement {
constructor() {
super();
const template = document.getElementById('my-template').content;
const shadow = this.attachShadow({ mode: 'open' });
shadow.appendChild(template.cloneNode(true));
}
}
customElements.define('template-component', TemplateComponent);
</script>
<template-component></template-component>
📌 解释:
<template>:里面的内容一开始不会被显示.cloneNode(true):复制模板内容并插入组件中
🎯 练习:修改模板中的文字样式,让它的字体大小变成 20px 并居中显示
四、实战项目:做一个天气卡片组件
接下来我们来做一个完整的 Web Components 实战项目:天气卡片组件 <weather-card>
这个组件将接收城市名作为属性,并展示模拟的天气数据。
步骤 1:定义组件结构
<!-- index.html -->
<weather-card city="北京"></weather-card>
步骤 2:编写组件代码
<script type="module">
class WeatherCard extends HTMLElement {
constructor() {
super();
this.city = this.getAttribute('city') || '未知城市';
this.temperature = Math.floor(Math.random() * 30 + 10); // 模拟温度
const shadow = this.attachShadow({ mode: 'open' });
const container = document.createElement('div');
container.className = 'card';
container.innerHTML = `
<h2>${this.city} 天气预报</h2>
<p>当前温度:${this.temperature}°C</p>
`;
const style = document.createElement('style');
style.textContent = `
.card {
border: 1px solid #ccc;
padding: 20px;
border-radius: 10px;
width: 250px;
background: #eaf4ff;
font-family: Arial, sans-serif;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
`;
shadow.appendChild(style);
shadow.appendChild(container);
}
}
customElements.define('weather-card', WeatherCard);
</script>
📌 运行结果: 你会看到一个带有城市名称和模拟温度的天气小卡片。
🎯 练习:给每个卡片添加一个图标(例如 ☀️ 或 ☁️),根据温度高低显示不同的表情符号
五、常见问题:新手常问的问题解答
Q1:为什么我的组件没显示?
- 确保你在调用
customElements.define()前没有使用那个标签 - 确保脚本正确执行(查看控制台是否有报错)
Q2:如何在组件中响应点击事件?
在 Shadow DOM 中添加事件监听器即可,例如:
button.addEventListener('click', () => alert('按钮被点击啦!'));
Q3:能不能用 JS 动态修改组件属性?
当然可以!你还可以用 observedAttributes 监听属性变化并更新组件。
Q4:和 Vue、React 比有什么区别?
Vue 和 React 是完整的前端框架,而 Web Components 是浏览器原生支持的技术,优点在于 不需要依赖任何库,组件可以跨框架使用。
六、学习建议:下一步该学什么?
✅ 掌握基础知识后可以继续学习以下内容:
生命周期方法
connectedCallback():组件插入 DOM 时触发disconnectedCallback():组件移除时触发attributeChangedCallback():属性变化时触发
CSS 变量和主题定制
- 利用 CSS 变量实现暗黑/明亮模式切换
组合多个 Web Components
- 把多个小组件组装成更大的界面
与现有框架结合
- 把你的组件集成到 Vue、React 项目中使用
打包发布 NPM 包
- 将你的组件包发布到 NPM,供别人使用
总结
Web Components 是一种让你“原生写组件”的方式,无需引入框架,也能做出高度可复用的组件。它简单、高效、兼容性强,是现代前端开发的重要方向之一。
从今天开始,你可以试着把常用的 UI 片段都封装成一个个漂亮的“积木”,然后像搭乐高一样快速构建网页!
🎯 课后任务:
创建一个你自己的组件库,包含至少 3 个常用组件(如按钮、标题、卡片等),并尝试在不同页面中复用它们!
如果你有任何问题,欢迎留言或者私信交流,我们一起进步 😄

评论 0