Web Components 实战:从原生 API 到跨框架复用
React、Vue、Angular 都在各自的生态里把组件化做得很顺手,但项目一旦跨框架,事情就没那么轻松了。公司里常见的情况是:老系统还在跑 jQuery,新项目可能是 Vue2/3,旁边又有一套 React。UI 规范想统一,代码却各写各的。这个时候,Web Components 的价值就很直接——它提供的是浏览器原生的组件标准,而不是某个框架自己的封装方式。
它不负责替代 React 或 Vue,更多是补上'组件能不能在不同技术栈里直接复用'这块短板。
先看一个最小实现
下面这个 <user-card> 组件只做两件事:接收 avatar 和 name,再把样式关在自己的作用域里。
// 1. 定义 HTML 模板
const template = document.createElement('template');
template.innerHTML = `
<style>
.card {
display: flex;
align-items: center;
padding: 16px;
border: 1px solid #eee;
border-radius: 8px;
}
img {
width: 50px;
height: 50px;
border-radius: 50%;
margin-right: 16px;
}
h3 {
margin: 0;
font-size: 18px;
}
</style>
<div class="card">
<img src="" alt="avatar" />
<div>
<h3></h3>
<slot name="desc"></slot>
</div>
</div>
`;
// 2. 创建自定义类
class UserCard extends HTMLElement {
constructor() {
super();
// 开启 Shadow DOM,实现样式隔离
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
// 3. 监听属性变化
static get observedAttributes() {
return ['avatar', 'name'];
}
() {
(name === ) {
..(). = newValue;
} (name === ) {
..(). = newValue;
}
}
}
..(, );


