๐ฐ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?