// ⭐️ 1️⃣ 定義一個繼承自 HTMLElement 的 class
class MyComponent extends HTMLElement {
constructor() {
// ⭐️ 呼叫父類別的 constructor
super();
// 在這裡初始化你的 component
}
}
constructor() {
super();
// ⭐️ 2️⃣ 建立 shadow DOM
// mode:
// - 'open' : 允許 JS 從外部訪問 shadow DOM
// - 'closed': 不允許
this.attachShadow({ mode: 'open' });
}
<!-- ⭐️ 3️⃣ 建立樣板 -->
<template id="my-component-template">
<style>
/* component 的樣式 */
.container {
border: 1px solid black;
padding: 10px;
}
</style>
<div class="container">
<h1>Hello from My Component!</h1>
<p>
<!-- <slot> 是一個 placeholder,允許使用者在 component 標籤內插入內容 -->
<slot></slot>
</p>
</div>
</template>
constructor() {
super();
this.attachShadow({ mode: 'open' });
// ⭐️ 4️⃣ append template content to shadow root
const template = document.getElementById('my-component-template');
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
// in constructor()
// ⭐️ 4️⃣ append template content to shadow root
this.shadowRoot.innerHTML = `
<style> ... </style>
<div class="container"> ... </div>
`;
// ⭐️ 5️⃣ 註冊 Component ╭──tag name──╮ ╭─ class ─╮
window.customElements.define('my-component', MyComponent);