Web Components与主流框架对比,谁才是未来的方向?
🧑🏫 作者:全栈老李
📅 更新时间:2025 年 6 月
🧑💻 适合人群:前端初学者、进阶开发者
🚀 版权:本文由全栈老李原创,转载请注明出处。
最近在Vue Conf上看到尤雨溪提到Web Components时意味深长的笑容,让我想起三年前第一次在Chrome里调试<my-button>
标签时的新奇感。当时我就意识到,这场关于前端组件化未来的讨论,远比我们想象的要复杂得多。(全栈老李)
当"原生派"遇上"框架党"
Web Components本质上是一组浏览器原生API的集合,主要包括:
- Custom Elements - 让你创造自己的HTML标签
- Shadow DOM - 组件样式的天然隔离
- HTML Templates - 声明式的模板片段
- ES Modules - 模块化加载方案
// 定义一个WC组件 - 全栈老李示例代码
class MyCounter extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: 'open' });
this.count = 0;
this.shadowRoot.innerHTML = `
<style>
button {
padding: 8px 16px;
background: #646cff;
color: white;
border: none;
border-radius: 4px;
}
</style>
<button>点击次数: ${
this.count}</button>
`;
}
connectedCallback() {
this.shadowRoot.querySelector('button')
.addEventListener('click', () => {
this.count