Web Component
CustomElementRegistry
is used to register new componentwindow.customElements
return an instance ofCustomElementRegistry
- Custom element is encapsulated through a Shadow DOM.
<template>
and<slot>
can be used to define markup template.
Define Web Component
customElements.define('word-count',
class extends HTMLElement {
constructor() {
super();
var parent = this.parentNode;
const shadow = this.attachShadow({mode: 'open'});
var text = document.createElement('span');
text.textContent = "some text";
showdow.appendChild(text);
}
}
);
使用一个定义好的 Web Component
<p>
Some paragraph text
<word-count></word-count>
<p>
Use Template
除了使用DOM API操作Component的Shadow Dom之外,还可以借助<template>
让定义变得更直观一些。
<template id="word-count-template">
<span>count text</span>
</template>
<script>
customElements.define('word-count',
class extends HTMLElement {
constructor() {
super();
var parent = this.parentNode;
const shadow = this.attachShadow({mode: 'open'});
const template = document.getElementById('word-count-template');
let content = template.content;
showdow.appendChild(content.cloneNode(true));
}
}
);
</script>
<template>
and <slot>
为了允许对Component进行局部的定制,<slot>
被用来进行占位和之后的插入。
<template id="word-count-template">
<slot name="icon"></slot><span>count text</span>
</template>
<word-count>
<img slot="icon" src="count.png">
</word-count>