参考链接
One of the key features of the Web Components standard is the ability to create custom elements that encapsulate your functionality on an HTML page, rather than having to make do with a long, nested batch of elements that together provide a custom page feature. This article introduces the use of the Custom Elements API.
Web Components一个关键的功能是在html 页面中创建实现了你的功能的自定义元素. 不必处理大量嵌套在一起的元素,这些元素一起提供了自定义页面功能。这个文章介绍Customer Element API的使用;
Note: Custom elements are supported by default in Firefox, Chrome, and Edge (76). Opera and Safari so far support only autonomous custom elements.
须知: Customer Element 现在已经被Firefox, chrome, Edge(76) 支持了。 Opera 和Safari 目前只支持autonomous custom elements;
There are two types of custom elements: 有两种类型的custom elements;
-
Autonomous custom elements are standalone — they don't inherit from standard HTML elements. You use these on a page by literally writing them out as an HTML element. For example , or document.createElement("popup-info").
-
Customized built-in elements inherit from basic HTML elements. To create one of these, you have to specify which element they extend (as implied in the examples above), and they are used by writing out the basic element but specifying the name of the custom element in the is attribute (or property). For example
, or document.createElement("p", { is: "word-count" }).
Autonomouse custom elements 使用例子
class MyBtn extends HTMLElement{
constructor(){
super();
let dom = document.createElement('div');
dom.innerHTML = this.hasAttribute('label') ? this.getAttribute('label') : 'ttt';
let style = document.createElement('style');
style.textContent = `div{ background-color: red}`;
this.appendChild(style);
this.appendChild(dom);
}
}
customElements.define('my-pop',MyBtn);
Customized built-in elements 使用例子
class IconButton extends HTMLButtonElement {
constructor(){
super();
let div = document.createElement('div');
div.innerHTML = 'sss'
this.append(div)
}
}
customElements.define('icon-button',IconButton,{
extends: 'button'
})
Using the lifecycle callback 使用生命周期回调方法
- connectedCallback: Invoked each time the custom element is appended into a document-connected element. This will happen each time the node is moved, and may happen before the element's contents have been fully parsed.
- disconnectedCallback: Invoked each time the custom element is disconnected from the document's DOM.
- adoptedCallback: Invoked each time the custom element is moved to a new document.
- attributeChangedCallback: Invoked each time one of the custom element's attributes is added, removed, or changed. Which attributes to notice change for is specified in a static get observedAttributes method
坑点
- javascript (定义组件不能在调用组件之前)实测会出现各种异常,例如无法获取 data-set,无法添加元素等...
- 如果不使用shadow dom 包括的话,非行内样式,是可能会渲染到全局的;