Web Components

随着Vue.jsReact 这类视图层解决方案的流行,组件化开发的优势越来越明显。浏览器原生支持的 Web Components 再次回到人们的视野。

Web Components 包含 3 个核心技术

  • Custom elements(自定义元素)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
customElements.define(
'custom-element',
class extends HTMLElement {
constructor() {
super();
// 自定义内容
}
connectedCallback() {
// 当自定义元素第一次被连接到文档DOM时被调用
}
disconnectedCallback() {
// 当自定义元素与文档DOM断开连接时被调用
}
adoptedCallback() {
// 当自定义元素被移动到新文档时被调用
}
attributeChangedCallback() {
// 当自定义元素的一个属性被增加、移除或更改时被调用
}
},
{
extends: '' // 指定继承的已创建的元素
}
);
  • Shadow DOM(影子 DOM)

需要提供宿主元素,外部的设置无法影响到其内部,而内部的设置也不会影响到外部。

1
const shadowRoot = element.attachShadow({ mode: 'open' }); // mode: 'open' | 'closed',控制element时候可以通过shadowRoot获取影子DOM
  • HTML templates(HTML 模板)

<template>标签可以包含 HTML 标签,不会被渲染

<slot>标签类比Vueslot实现,提供模板占位符作用

1
2
3
4
5
6
7
8
<template id="template">
<div>
<h2>Template</h2>
<slot></slot>
<!--具名插槽-->
<slot name="slot-name">DEFAULT NAME</slot>
</div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
customElements.define(
'custom-element',
class extends HTMLElement {
constructor() {
super();
let template = document.getElementById('template');
let templateContent = template.content;
const shadowRoot = this.attachShadow({ mode: 'open' }).appendChild(
templateContent.cloneNode(true)
);
}
}
);