Web Components 标准
Web Components三件套:Custom Elements自定义元素(customElements.define)、Shadow DOM隔离样式、HTML Templates模板、Lit轻量库、与React/Vue组件对比 · 难度:入门 · +10XP
Web Components —— 创建自定义HTML标签
你可以创建自己的HTML标签,比如<user-avatar>或<my-calendar>。Web Components是一组浏览器原生API,让你封装可复用的自定义元素——不需要React或Vue。
Custom Elements
class MyCounter extends HTMLElement {
constructor() {
super();
this.count = 0;
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = '';
this.shadowRoot.querySelector('button').onclick = () => {
this.count++;
this.shadowRoot.querySelector('button').textContent = '点击了' + this.count + '次';
};
}
}
customElements.define('my-counter', MyCounter);
直接在HTML中使用:<my-counter></my-counter>
动手练习
- 基础练习:创建一个<hello-world>自定义元素。
- 进阶应用:用Shadow DOM封装一个<user-card>,内部样式不受外部CSS影响。
- 项目实战:把常用UI组件封装为Web Component,实现跨框架复用。