⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

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>

动手练习

  1. 基础练习:创建一个<hello-world>自定义元素。
  2. 进阶应用:用Shadow DOM封装一个<user-card>,内部样式不受外部CSS影响。
  3. 项目实战:把常用UI组件封装为Web Component,实现跨框架复用。
Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 231 篇
0 完成
🔥 0