๐Ÿ”ฐweb component

web โŸฉ component

ๅฎฃๅ‘Šๆ–นๅผ

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?