🔰web component
web ⟩ component
Web component 讓你自定 HTML 元素 (custom element),封裝 HTML 結構、CSS 樣式和 JavaScript 行為。
📁 自訂元素 (custom element)
// ⭐️ 1️⃣ 宣告自訂元素
class MyComponent extends HTMLElement {
// constructor
constructor() {
super();
// ⭐️ 2️⃣ 建立 shadow DOM
this.attachShadow({ mode: 'open' }); // returns a reference to this.shadowRoot
// ⭐️ 3️⃣ 建立樣板 4️⃣ 複製樣板內容到 shadow root
this.shadowRoot.innerHTML = `
<style> ... </style>
<div class="container"> ... </div>
`;
}// end of constructor()
}// end of MyComponent
// ⭐️ 5️⃣ 註冊標籤 ╭──tag name──╮ ╭─ class ─╮
window.customElements.define('my-component', MyComponent);📁 自訂內建元素 (customized built-in element)
Lit (Google)
client-side JavaScript timeline - web components are not defined until fully loaded.
問:「attachShadow() 應該放在 constructor() 還是 connectedCallback()❓」
宣告方式
1️⃣ 定義 custom element
先定義一個繼承 HTMLElement 的 custom element (class):
// ⭐️ 1️⃣ custom element
class MyComponent extends HTMLElement {
constructor() {
// ⭐️ 呼叫父類別的 constructor
super();
// 在這裡初始化你的 component
}
}2️⃣ 建立 Shadow DOM
Shadow DOM 為 web component 建立一個封裝的 DOM 樹 (encapsulated DOM tree),讓內部的樣式 (CSS styles) 和腳本 (JS scripts) 不會影響到外面 (light DOM) 的其他部分,反之亦然。
constructor() {
super();
// ⭐️ 2️⃣ 建立 shadow DOM
// mode:
// - 'open' : 允許 JS 從外部訪問 shadow DOM
// - 'closed': 不允許
this.attachShadow({ mode: 'open' });
}3️⃣ 建立樣板:以下提供三個方式建立 <template>
使用方式
📁 HTML:使用自訂元素 (custom element)
📁 JS:定義並宣告
📁 JS:定義並宣告
📁 HTML:使用自訂內建元素 (customized built-in element)
📁 JS:使用自訂內建元素
Calculator ❤️
Last updated
Was this helpful?