🔰web component
web ⟩ component
Web component 讓你自定 HTML 元素 (custom element),封裝 HTML 結構、CSS 樣式和 JavaScript 行為。
宣告方式
1️⃣ 定義 custom element
先定義一個繼承 HTMLElement 的 custom element (class):
// ⭐️ 1️⃣ custom element
class MyComponent extends HTMLElement {
constructor() {
// ⭐️ 呼叫父類別的 constructor
super();
// 在這裡初始化你的 component
}
}
使用方式
📁 HTML:使用自訂元素 (custom element)
<!-- ⭐️ custom element -->
<my-component>
<!-- slotted nodes -->
</my-component>
📁 JS:定義並宣告
// ⭐️ autonomous custom element ---------------
// autonomous:獨立存在的(非內建的,如:HTMLButtonElement 等)
class MyComponent extends HTMLElement {
// constructor
constructor() {
// tell HTMLElement to initialize itself.
super();
// get `width`, `height` attributes
const height = this.getAttribute('height') || '100px';
const width = this.getAttribute('width') || '100px';
// ...
}
// connected to document
connectedCallback() {
// attach shadow root
let root = this.attachShadow({mode: 'open'});
// ⭐️ clone nodes from <template>
let clone = tmpl.content.cloneNode(true);
root.append( clone );
// ...
}
// template HTML
static template(height, width) {
return `
<style>
.placeholder {
background-color: pink;
width: ${height};
height: ${width};
}
</style>
<div class='placeholder'>Placeholder</div>
`;
}
}
// ⭐️ register <my-component>
// ⭐️⭐️ custom element names must contain a "hyphen".
// ╭──tag name──╮ ╭─ class ─╮
customElements.define('my-component', MyComponent);
Last updated
Was this helpful?