🔸custom element

browserweb componentsimplement ⟩ custom elements

associate a JavaScript class with an HTML tag name.

custom element name 中間一定要有:"-"

  • 例如:<vstack-><v-stack>

  • 但 "-" 不能放前面:<-vstack>

define new custom elements with customElements.define().

// define new custom element
customElements.define(
  'web-component',                    // ⭐️ HTML tag name, must have "-"❗️ 
  class extends HTMLElement { ... }   // ⭐️ must extend `HTMLElement`❗️ 
);

custom elements render as inline elements by default.

Valid Custom Element Name

  • 開頭:[a-z] ⭐️

  • 接著:[0-9], [a-z], "-", ".", "_" (optional)

  • 中間一定要有:"-" ⭐️

  • 接著:[0-9], [a-z], "-", ".", "_" (optional)

<vstack-> 或 <i-vstack> ❓(這兩個都是合法的名字)

PotentialCustomElementName ::= 
    [a-z] (PCENChar)* '-' (PCENChar)*
    
PCENChar ::=
    "-" | "." | [0-9] | "_" | [a-z] | #xB7 | 
    [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x37D] | [#x37F-#x1FFF] | 
    [#x200C-#x200D] | [#x203F-#x2040] | [#x2070-#x218F] | 
    [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | 
    [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]

Register New Tag Name

We can create our tags by using the CustomElementRegistry object (window.customElements).

  • custom element names must contain a hyphen 📘 customElements.define()

  • Custom elements cannot be self-closing because HTML only allows a few elements to be self-closing. Always write a closing tag (<custom-element></custom-element>) 📘 Google ⟩ Custom Elements

// ⭐️ custom tag <my-component>
// ⭐️ custom element names must contain a "hyphen".
customElements.define('my-component', MyComponent);

Supporting Class

To create a custom element, we need to tell the browser several details about it: how to show it, what to do when the element is added or removed to page, etc.

class MyComponent extends HTMLElement {

  constructor() {
    super();
    // ...
  }

  // triggered when added to the document
  connectedCallback() {}

  // triggered when removed from the document
  disconnectedCallback() {}

  // attribute names to monitor for changes
  static get observedAttributes() {
    return [ /* ... */ ];
  }

  // triggered when one of attributes listed above is modified.
  // doesn’t trigger for unlisted attributes (for performance reasons).
  attributeChangedCallback(name, oldValue, newValue) {}

  // called when moved to a new document
  // happens in document.adoptNode, very rarely used
  adoptedCallback() {}

  // other methods and properties ...
}

Last updated