├── LICENSE
├── components
├── button.js
└── modal.js
├── index.html
└── readme.md
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 MrXujiang
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/components/button.js:
--------------------------------------------------------------------------------
1 | class Button extends HTMLElement {
2 | constructor() {
3 | super();
4 | // 获取模板内容
5 | let template = document.getElementById('btn_tpl');
6 | let templateContent = template.content;
7 |
8 | const shadowRoot = this.attachShadow({ mode: 'open' });
9 | const btn = document.createElement('button');
10 | btn.appendChild(templateContent.cloneNode(true));
11 | btn.setAttribute('class', 'xu-button');
12 | // 定义并获取按钮类型 primary | warning | default
13 | const type = {
14 | 'primary': '#06c',
15 | 'warning': 'red',
16 | 'default': '#f0f0f0'
17 | }
18 | const btnType = this.getAttribute('type') || 'default';
19 | const btnColor = btnType === 'default' ? '#888' : '#fff';
20 |
21 | // 创建样式
22 | const style = document.createElement('style');
23 | // 为shadow Dom添加样式
24 | style.textContent = `
25 | .xu-button {
26 | position: relative;
27 | margin-right: 3px;
28 | display: inline-block;
29 | padding: 6px 20px;
30 | border-radius: 30px;
31 | background-color: ${type[btnType]};
32 | color: ${btnColor};
33 | outline: none;
34 | border: none;
35 | box-shadow: inset 0 5px 10px rgba(0,0,0, .3);
36 | cursor: pointer;
37 | }
38 | `
39 | shadowRoot.appendChild(style);
40 | shadowRoot.appendChild(btn);
41 | // shadowRoot.appendChild(pElem);
42 | }
43 | attributeChangedCallback(name, oldValue, newValue) {
44 | console.log('changed.', name, oldValue, newValue);
45 | }
46 | }
47 | customElements.define('xu-button', Button);
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Web Component
7 |
8 |
9 | Web Component 实战 - 趣谈前端-徐小夕
10 | 1. Button
11 | 趣谈button
12 | 趣谈button
13 | 趣谈button
14 | 2. Modal
15 | 显示弹窗
16 | 关闭弹窗
17 | web component 实现一个有点意思的modal组件?
18 |
19 |
20 |
21 | button content
22 |
23 |
24 |
32 |
33 | modal content
34 |
35 |
36 |
37 |
38 |
47 |
48 |
--------------------------------------------------------------------------------
/components/modal.js:
--------------------------------------------------------------------------------
1 | class Modal extends HTMLElement {
2 | constructor() {
3 | super();
4 | // 获取模板内容
5 | let template = document.getElementById('modal_tpl');
6 | let templateContent = template.content;
7 |
8 | const shadowRoot = this.attachShadow({ mode: 'open' });
9 | const wrap = document.createElement('div');
10 | const modal = document.createElement('div');
11 | const header = document.createElement('header');
12 | const btnClose = document.createElement('span');
13 | const mask = document.createElement('div');
14 | const footer = document.createElement('footer');
15 | const btnCancel = document.createElement('xu-button');
16 | const btnOk = document.createElement('xu-button');
17 |
18 | // wrap
19 | wrap.setAttribute('class', 'wrap');
20 |
21 | // modal
22 | modal.setAttribute('class', 'xu-modal');
23 |
24 | // header
25 | let title = this.getAttribute('title');
26 | header.textContent = title;
27 | btnClose.setAttribute('class', 'xu-close');
28 | btnClose.textContent = 'x';
29 | header.appendChild(btnClose);
30 | modal.appendChild(header);
31 |
32 | btnClose.addEventListener('click', () => {
33 | wrap.style.display = 'none';
34 | })
35 |
36 | // content
37 | modal.appendChild(templateContent.cloneNode(true));
38 |
39 | // footer
40 | btnOk.setAttribute('type', 'primary');
41 | const slot1 = document.createElement('span');
42 | slot1.setAttribute('slot', 'btn-content');
43 | slot1.textContent = '确认';
44 | btnOk.appendChild(slot1);
45 |
46 | const slot2 = document.createElement('span');
47 | slot2.setAttribute('slot', 'btn-content');
48 | slot2.textContent = '取消';
49 | btnCancel.appendChild(slot2);
50 |
51 | footer.appendChild(btnCancel);
52 | footer.appendChild(btnOk);
53 | modal.appendChild(footer);
54 |
55 | // mask
56 | mask.setAttribute('class', 'mask');
57 | wrap.appendChild(mask);
58 | wrap.appendChild(modal);
59 |
60 | // 创建样式
61 | const style = document.createElement('style');
62 | const width = this.getAttribute('width');
63 | const isVisible = this.getAttribute('visible');
64 | // 为shadow Dom添加样式
65 | style.textContent = `
66 | .wrap {
67 | position: fixed;
68 | left: 0;
69 | right: 0;
70 | bottom: 0;
71 | top: 0;
72 | display: ${isVisible === 'true' ? 'block' : 'none'}
73 | }
74 | .xu-modal {
75 | position: absolute;
76 | z-index: 500;
77 | left: 50%;
78 | top: 50%;
79 | transform: translate(-50%, -50%);
80 | width: ${width};
81 | box-shadow: 0 0 20px rgba(0,0,0, .2);
82 | background: #fff;
83 | border-radius: 3px;
84 | }
85 | header {
86 | padding: 10px 20px;
87 | border-bottom: 1px solid #f0f0f0;
88 | font-weight: bold;
89 | background: #f0f0f0;
90 | }
91 | .xu-close {
92 | float: right;
93 | color: #ccc;
94 | cursor: pointer;
95 | }
96 | footer {
97 | margin-top: 20px;
98 | border-top: 1px solid #f0f0f0;
99 | padding: 10px 20px;
100 | text-align: right;
101 | }
102 | .mask {
103 | position: fixed;
104 | left: 0;
105 | right: 0;
106 | bottom: 0;
107 | top: 0;
108 | background: rgba(0,0,0, .3);
109 | z-index: 100;
110 | }
111 | `
112 | shadowRoot.appendChild(style);
113 | shadowRoot.appendChild(wrap);
114 | }
115 | connectedCallback(el) {
116 | console.log('insert dom', el)
117 | }
118 | disconnectedCallback() {
119 | console.log('Custom square element removed from page.');
120 | }
121 | adoptedCallback() {
122 | console.log('Custom square element moved to new page.');
123 | }
124 | attributeChangedCallback(name, oldValue, newValue) {
125 | if(oldValue) {
126 | const childrenNodes = this.shadowRoot.childNodes;
127 | for(let i = 0; i < childrenNodes.length; i++) {
128 | if(childrenNodes[i].nodeName === 'DIV' && childrenNodes[i].className === 'wrap') {
129 | if(newValue === 'true') {
130 | childrenNodes[i].style.display = 'block';
131 | }else {
132 | childrenNodes[i].style.display = 'none';
133 | }
134 | }
135 | }
136 | }
137 | }
138 | // 如果需要在元素属性变化后,触发 attributeChangedCallback()回调函数,
139 | // 你必须监听这个属性。这可以通过定义observedAttributes() get函数来实现
140 | static get observedAttributes() {
141 | return ['visible'];
142 | }
143 | }
144 | customElements.define('xu-modal', Modal);
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | 
2 | ## 前言
3 | 作为一名前端工程师,我们每天都在和组件打交道,我们也许基于**react/vue**使用过很多第三方组件库,比如**ant design**,**elementUI**,**iView**等,或者基于它们进行过组件的二次开发,比如**业务组件**,**UI组件**等,亦或者觉得团队能力很强,可以不依赖第三方而独立开发属于自己的组件库。无论何种形式,组件开发已然成为我们工作中的必备技能,为了更好的复用性和可维护性,组件化开发是必然选择,也正是因为组件化开发越来越重要,几年前web标准推出了**Web Component**这一概念,意在解决html原生标记语言复用性的问题。
4 |
5 | 目前**vue**或者**react**框架中也支持使用**Web Component**,而且在**Web Component**中也可以动态的调用**react**或者**vue**的api来实现组件或页面的渲染,这给我们开发者提供了更大的自由度,从而在日益复杂的项目中能使用更加灵活且优雅的方式来进行组件化开发。
6 |
7 | 我们使用**Web Component**可以通过原生的方式来实现组件化而不依赖与vue或者react这些第三方框架,并且现代浏览器对其支持还算不错,相信未来**Web Component**将会成为组件开发的趋势。所以接下来笔者将会带大家一步步来学习**Web Component**,并且使用**Web Component**实现两个常用组件:
8 | * **Button**
9 | * **Modal**
10 |
11 | 大家在掌握了**Web Component**之后可以开发更多自定义组件,那么写下来就来学习一下吧。
12 |
13 | ## 正文
14 | 在开始正文之前笔者还想多啰嗦一下,也是之前有很多朋友问我的问题:**如何在公司平衡好工作和成长?**
15 |
16 | 其实笔者也经历过这种迷茫期,之前因为公司业务繁忙而不得不忙于编写业务代码,几乎没有时间去学习和成长。有些时候项目做完之后又有新的需求要处理,感觉瞬间被掏空。(B端产品为了满足客户需求往往在产品把控上很难做取舍,因为客户就是上帝, 所以工程师和产品的关系很微妙~)
17 | 
18 | 一般情况下遇到以上的情景,作为一个合格的企业员工的,当然是业务和任务优先,在完成工作之后再去考虑成长和学习。当然公司也不会一直这么忙,所以当空闲的时候,我们可以好好利用(当然偶尔刷刷手机也是允许的,取决于个人)。
19 |
20 | 另一方面,我们可以通过提高工作效率来压缩工作时间,因为业务代码做多了总会有点规律和总结,如果整体架构设计的好,一般第一次做过了,第二次再遇到类似的业务几乎“秒关”,这一块对于前端来说,组件系统和模块化尤其重要;对于后端来说,微服务是很好的例子。
21 |
22 | 所以说如何学习和成长,以上两点是笔者3年工作的总结,希望能给大家以启发。
23 |
24 | 另一个问题就是如何快速掌握新技术?这个答案在这篇文章结束后,大家也许会明白些许。
25 |
26 | 好了,废话到此为止,接下来进入我们的**Web Component**实战。笔者对其知识点梳理成如下的思维导图:
27 | 
28 |
29 | ### 1. Web Component基础知识
30 | **Web Components**主要由三项技术组成,分别为
31 | * **Custom elements(自定义元素)**
32 | * **Shadow DOM(影子DOM)**
33 | * **HTML templates(HTML模板)**
34 |
35 | 它们可以一起使用来创建功能强大的定制元素,并且可以在我们喜欢的任何地方重用,不必担心代码冲突。接下来笔者就分别介绍这三项技术。
36 |
37 | #### 1.1 Custom elements(自定义元素)
38 | **custom elements**也就是我们常说的自定义标签,它主要通过**CustomElementRegistry**接口来定义,**CustomElementRegistry.define(name, class, extends)** 方法用来注册一个**custom element**,该方法接受以下参数:
39 |
40 | * **name** 所创建的元素名称,且需符合 DOMString 标准的字符串。注意,custom element 的名称不能是单个单词,且其中必须要有短横线
41 | * **class** 用于定义元素行为的类
42 | * **extends** 可选参数,一个包含 extends 属性的配置对象,指定了所创建的元素继承自哪个内置元素,可以继承任何内置元素。
43 |
44 | 具体案例如下:
45 | ``` js
46 | customElements.define(
47 | 'word-count',
48 | class WordCount extends HTMLParagraphElement {
49 | constructor() {
50 | super();
51 |
52 | // 元素的功能代码
53 | ...
54 | }
55 | }, { extends: 'p' });
56 | ```
57 | 接下来另一个比较重要的知识点就是**custom element**的**生命周期回调函数**,具体介绍如下:
58 | * **connectedCallback**:当 custom element首次被插入文档DOM时,被调用
59 | * **disconnectedCallback**:当 custom element从文档DOM中删除时,被调用
60 | * **adoptedCallback**:当 custom element被移动到新的文档时,被调用
61 | * **attributeChangedCallback**: 当 custom element增加、删除、修改自身属性时,被调用
62 |
63 | 大家可以先理解一下生命周期函数的用法,在下面的组件实战中会有详细的应用。
64 |
65 | #### 1.2 Shadow DOM(影子DOM)
66 | **Shadow DOM** 接口可以将一个隐藏的、独立的 DOM附加到一个元素上,并且允许将隐藏的 DOM 树附加到常规的 DOM 树中:**以 shadow root 节点为起始根节点,在这个根节点的下方,可以是任意元素,和普通的 DOM 元素一样**。MDN对其有一张详细的草图方便大家理解:
67 | 
68 | 上图中4个术语意思如下:
69 | * Shadow host:一个常规 DOM节点,Shadow DOM 会被附加到这个节点上。
70 | * Shadow tree:Shadow DOM内部的DOM树。
71 | * Shadow boundary:Shadow DOM结束的地方,也是常规 DOM开始的地方。
72 | * Shadow root: Shadow tree的根节点
73 |
74 | 如果我们想将一个 **Shadow DOM** 附加到 custom element 上,可以在 custom element 的构造函数中添加如下实现:
75 | ``` js
76 | class Button extends HTMLElement {
77 | constructor() {
78 | super();
79 | let shadow = this.attachShadow({mode: 'open'});
80 | }
81 | }
82 | ```
83 | 我们将 Shadow DOM 附加到一个元素之后,可以使用 DOM APIs对它进行操作,如下:
84 | ``` js
85 | class Button extends HTMLElement {
86 | constructor() {
87 | super();
88 | let shadow = this.attachShadow({mode: 'open'});
89 | let para = document.createElement('p');
90 | shadow.appendChild(para);
91 | }
92 | }
93 | ```
94 | 我们甚至可以将样式插入到Shadow DOM中, 如下:
95 | ``` js
96 | let style = document.createElement('style');
97 |
98 | style.textContent = `
99 | .btn-wrapper {
100 | position: relative;
101 | }
102 | .btn {
103 | // ...
104 | }
105 | `
106 |
107 | shadow.appendChild(style);
108 | ```
109 | 以上是定义组件的最基本方式,一个完整的demo如下:
110 | ``` js
111 | class Button extends HTMLElement {
112 | constructor() {
113 | super();
114 | let shadow = this.attachShadow({mode: 'open'});
115 | let para = document.createElement('p');
116 | shadow.appendChild(para);
117 | let style = document.createElement('style');
118 |
119 | style.textContent = `
120 | .btn-wrapper {
121 | position: relative;
122 | }
123 | .btn {
124 | // ...
125 | }
126 | `
127 |
128 | shadow.appendChild(style);
129 | }
130 | }
131 | customElements.define('xu-button', Button);
132 | ```
133 | #### 1.3 HTML templates(HTML模板)
134 | \ 和 \ 元素可以用来灵活填充 Web组件的 shadow DOM 的模板.它们的使用很简单,有点类似于**vue**的**template**和**slot**。一个简单的tempalte例子如下:
135 | ``` html
136 |
137 | 趣谈前端
138 |
139 | ```
140 | 我们可以用 **JavaScript** 获取它的引用,然后添加到DOM中,代码如下:
141 | ``` js
142 | let template = document.getElementById('xu_tpl');
143 | let templateContent = template.content;
144 | document.body.appendChild(templateContent);
145 | ```
146 |
147 | 至于slot,使用和vue的slot有点类似,主要提供一种插槽机制,比如我们在模版中定义一个插槽:
148 | ``` html
149 |
150 | 趣谈插槽
151 |
152 | ```
153 | 我们可以这么使用slot:
154 | ``` html
155 |
156 | 趣谈前端,让前端更有料!
157 |
158 | ```
159 | 介绍完基本概念之后,我们开始实战开发。
160 | ### 2. Web Component组件开发实战
161 | 在开发之前,我们先来看看实现效果:
162 | 
163 | 
164 | 第一张图是我们的自定义按钮组件(**Button**), 图二是笔者实现的弹窗(**modal**)组件。感觉还算有模有样,我们只需要引入这几个组件,即可在项目中使用,代码的目录结构如下:
165 | 
166 | 接下来我们就开始实现它们吧。
167 |
168 | #### 2.1 Button组件实现
169 | 我们像任何vue或者react组件一样,在设计组件之前一定要界定组件的边界和功能点,笔者在之前的[从0到1教你搭建前端团队的组件系统(高级进阶必备)](https://juejin.im/post/5e4d3a8de51d45270a709954)也有系统的介绍,这里就不在介绍了。
170 |
171 | 我们实现一个可以定制主题并且可以插入任意内容的**Button**组件,利用上面将的知识点,要实现插入自定义内容,我们可以使用**template和slot**, 首先定义template和slot,代码如下:
172 | ``` html
173 |
174 | button content
175 |
176 | ```
177 | 要想首先自定义按钮主题,我们可以通过**props**来实现用户控制,就像**antd**的**Button**组件,支持**primary**,**warning**等类型,具体实现如下:
178 | ``` js
179 | // Button.js
180 | class Button extends HTMLElement {
181 | constructor() {
182 | super();
183 | // 获取模板内容
184 | let template = document.getElementById('btn_tpl');
185 | let templateContent = template.content;
186 |
187 | const shadowRoot = this.attachShadow({ mode: 'open' });
188 | const btn = document.createElement('button');
189 | btn.appendChild(templateContent.cloneNode(true));
190 | btn.setAttribute('class', 'xu-button');
191 | // 定义并获取按钮类型 primary | warning | default
192 | const type = {
193 | 'primary': '#06c',
194 | 'warning': 'red',
195 | 'default': '#f0f0f0'
196 | }
197 | const btnType = this.getAttribute('type') || 'default';
198 | const btnColor = btnType === 'default' ? '#888' : '#fff';
199 |
200 | // 创建样式
201 | const style = document.createElement('style');
202 | // 为shadow Dom添加样式
203 | style.textContent = `
204 | .xu-button {
205 | position: relative;
206 | margin-right: 3px;
207 | display: inline-block;
208 | padding: 6px 20px;
209 | border-radius: 30px;
210 | background-color: ${type[btnType]};
211 | color: ${btnColor};
212 | outline: none;
213 | border: none;
214 | box-shadow: inset 0 5px 10px rgba(0,0,0, .3);
215 | cursor: pointer;
216 | }
217 | `
218 | shadowRoot.appendChild(style);
219 | shadowRoot.appendChild(btn);
220 | }
221 | }
222 | customElements.define('xu-button', Button);
223 | ```
224 | 在构造函数中,我们会定义元素实例所拥有的全部功能。通过用户传入的**type**属性来在**Button**组件挂载前设置其类型。对于自定义的插槽,我们可以通过**template.content**来获取其内容,然后插入**shadowRoot**中使其拥有**slot**能力。具体使用如下:
225 | ``` html
226 | 趣谈button
227 | 趣谈button
228 | 趣谈button
229 | ```
230 | 我们的Button组件拥有大部分原生dom的能力,包括dom操作,事件等,如下所示我们给自定义Button添加点击事件:
231 | ``` js
232 | document.querySelector('#btn_show').addEventListener('click', () => {
233 | modal.setAttribute('visible', 'true');
234 | }, false)
235 | ```
236 | #### 2.2 Modal组件实现
237 | **Modal**组件的实现和**Button**原理类似,不过过程稍微复杂一点,我们需要考虑**Modal**内容的插槽,**Modal**的显示和隐藏的控制等,如下图所示:
238 | 
239 | 具体的dom实现细节笔者就不一一介绍了,大家可以有不同的实现。我们主要来关注关闭按钮的逻辑和插槽。
240 |
241 | 首先title内容我们可以通过**props**来传递,**Modal**的内容插槽如下:
242 | ``` html
243 |
244 |
252 |
253 | modal content
254 |
255 |
256 | ```
257 | 由上可以看出tempalte我们定义了内部样式,很多复杂的**Web Component**组件也可以采用类似的设计去实现。这里我们就简单定义如上。
258 |
259 | 接下来的重点是关闭按钮和控制**Modal显示和隐藏**的逻辑,这块逻辑我们应该放在**Modal**组件内部来实现,我们不可能通过外部操作dom样式来控制**Modal**的显示和隐藏。我们先来回忆一下,**antd**组件或者**elementUI**的**Modal**可以通过传入**visible**属性来控制**Modal**的显示和隐藏,而且我们点击右上角的关闭按钮时,可以不改变任何属性的情况下关闭**Modal**,那么我们想想是怎么做到的呢?我们在**Web Component**组件内部,又能如何实现这一逻辑呢?
260 |
261 | 其实我们可以利用笔者上面介绍的**Web Component**组件生命周期来解决这一问题。首先对于关闭按钮来说,我们可以绑定一个事件,通过控制内部样式来让**Modal**隐藏。对于用户在外部修改了**visible**属性,我们如何让它自动随着**visible**的变化而显示或者隐藏呢?
262 |
263 | 我们可以利用**attributeChangedCallback**这个生命周期函数,并配合**observedAttributes**这一静态方法来实现自动监听。我们可以在**observedAttributes**中监听**visible**属性的变化,一旦该属性被修改,就会自动触发**attributeChangedCallback**。 具体代码如下:
264 | ``` js
265 | attributeChangedCallback(name, oldValue, newValue) {
266 | if(oldValue) {
267 | const childrenNodes = this.shadowRoot.childNodes;
268 | for(let i = 0; i < childrenNodes.length; i++) {
269 | if(childrenNodes[i].nodeName === 'DIV' && childrenNodes[i].className === 'wrap') {
270 | if(newValue === 'true') {
271 | childrenNodes[i].style.display = 'block';
272 | }else {
273 | childrenNodes[i].style.display = 'none';
274 | }
275 | }
276 | }
277 | }
278 | }
279 | // 如果需要在元素属性变化后,触发 attributeChangedCallback()回调函数,
280 | // 你必须监听这个属性。这可以通过定义observedAttributes() get函数来实现
281 | static get observedAttributes() {
282 | return ['visible'];
283 | }
284 | ```
285 | 以上代码中之所以要判断**oldValue**值是否存在, 是因为在实现第一次渲染时由于**visible**被赋值也会触发**attributeChangedCallback**,所以为了避免第一次执行该函数, 我们会控制只有**oldValue**值存在时才执行更新操作。
286 |
287 | **Modal**组件的难点攻克了,剩下的就很好实现了,接下来是笔者实现的**Modal**组件,代码如下:
288 | ``` js
289 | class Modal extends HTMLElement {
290 | constructor() {
291 | super();
292 | // 获取模板内容
293 | let template = document.getElementById('modal_tpl');
294 | let templateContent = template.content;
295 |
296 | const shadowRoot = this.attachShadow({ mode: 'open' });
297 | const wrap = document.createElement('div');
298 | const modal = document.createElement('div');
299 | const header = document.createElement('header');
300 | const btnClose = document.createElement('span');
301 | const mask = document.createElement('div');
302 | const footer = document.createElement('footer');
303 | const btnCancel = document.createElement('xu-button');
304 | const btnOk = document.createElement('xu-button');
305 |
306 | // wrap
307 | wrap.setAttribute('class', 'wrap');
308 |
309 | // modal
310 | modal.setAttribute('class', 'xu-modal');
311 |
312 | // header
313 | let title = this.getAttribute('title');
314 | header.textContent = title;
315 | btnClose.setAttribute('class', 'xu-close');
316 | btnClose.textContent = 'x';
317 | header.appendChild(btnClose);
318 | modal.appendChild(header);
319 |
320 | btnClose.addEventListener('click', () => {
321 | wrap.style.display = 'none';
322 | })
323 |
324 | // content
325 | modal.appendChild(templateContent.cloneNode(true));
326 |
327 | // footer
328 | btnOk.setAttribute('type', 'primary');
329 | const slot1 = document.createElement('span');
330 | slot1.setAttribute('slot', 'btn-content');
331 | slot1.textContent = '确认';
332 | btnOk.appendChild(slot1);
333 |
334 | const slot2 = document.createElement('span');
335 | slot2.setAttribute('slot', 'btn-content');
336 | slot2.textContent = '取消';
337 | btnCancel.appendChild(slot2);
338 |
339 | footer.appendChild(btnCancel);
340 | footer.appendChild(btnOk);
341 | modal.appendChild(footer);
342 |
343 | // mask
344 | mask.setAttribute('class', 'mask');
345 | wrap.appendChild(mask);
346 | wrap.appendChild(modal);
347 |
348 | // 创建样式
349 | const style = document.createElement('style');
350 | const width = this.getAttribute('width');
351 | const isVisible = this.getAttribute('visible');
352 | // 为shadow Dom添加样式
353 | style.textContent = `
354 | .wrap {
355 | position: fixed;
356 | left: 0;
357 | right: 0;
358 | bottom: 0;
359 | top: 0;
360 | display: ${isVisible === 'true' ? 'block' : 'none'}
361 | }
362 | // 忽略部分样式
363 | `
364 | shadowRoot.appendChild(style);
365 | shadowRoot.appendChild(wrap);
366 | }
367 | connectedCallback(el) {
368 | console.log('insert dom', el)
369 | }
370 | disconnectedCallback() {
371 | console.log('Custom square element removed from page.');
372 | }
373 | adoptedCallback() {
374 | console.log('Custom square element moved to new page.');
375 | }
376 | attributeChangedCallback(name, oldValue, newValue) {
377 | if(oldValue) {
378 | const childrenNodes = this.shadowRoot.childNodes;
379 | for(let i = 0; i < childrenNodes.length; i++) {
380 | if(childrenNodes[i].nodeName === 'DIV' && childrenNodes[i].className === 'wrap') {
381 | if(newValue === 'true') {
382 | childrenNodes[i].style.display = 'block';
383 | }else {
384 | childrenNodes[i].style.display = 'none';
385 | }
386 | }
387 | }
388 | }
389 | }
390 | // 如果需要在元素属性变化后,触发 attributeChangedCallback()回调函数,
391 | // 你必须监听这个属性。这可以通过定义observedAttributes() get函数来实现
392 | static get observedAttributes() {
393 | return ['visible'];
394 | }
395 | }
396 | customElements.define('xu-modal', Modal);
397 | ```
398 | 更详细的代码笔者已经上传到github了,大家感兴趣可以clone到本地运行体验一下,效果还是相当不错的。
399 |
400 | github地址: [Web Component实战demo](https://github.com/MrXujiang/WebComponent)
401 | ## 最后
402 | 如果想学习更多**前端技能**,**实战**和**学习路线**, 欢迎在公众号《趣谈前端》加入我们的技术群一起学习讨论,共同探索前端的边界。
403 | 
404 |
405 | ## 更多推荐
406 | * [当后端一次性丢给你10万条数据, 作为前端工程师的你,要怎么处理?](https://juejin.im/post/5edf34c4f265da76e609ed00)
407 | * [基于Apify+node+react/vue搭建一个有点意思的爬虫平台](https://juejin.im/post/5ebcbec96fb9a0437055c5ac)
408 | * [程序员必备的几种常见排序算法和搜索算法总结](https://juejin.im/post/5e9d47d4e51d4546c03843e9)
409 | * [基于nodeJS从0到1实现一个CMS全栈项目(上)](https://juejin.im/post/5d8af4cd6fb9a04e0925f3d8)
410 | * [基于nodeJS从0到1实现一个CMS全栈项目(中)(含源码)](https://juejin.im/post/5d8c7b66518825761b4c1e04)
411 | * [CMS全栈项目之Vue和React篇(下)(含源码)](https://juejin.im/post/5d8f4ee55188252cdb5e3125)
412 | * [从零到一教你基于vue开发一个组件库](https://juejin.im/post/5e63d1c36fb9a07cb427e2c2)
413 | * [从0到1教你搭建前端团队的组件系统(高级进阶必备)](https://juejin.im/post/5e4d3a8de51d45270a709954)
414 | * [10分钟教你手写8个常用的自定义hooks](https://juejin.im/post/5e57d0dfe51d4526ce6147f2)
--------------------------------------------------------------------------------