web component

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>

<my-btn click-fnname="whenClick">
<div slot="text" class="text">123</div>
</my-btn>
<template class="template">
<style>
/* 指代当前宿主 */
:host {
display: block;
width: 100px;
height: 40px;
border: 1px solid rgba(0, 0, 0, .4);
border-radius: 10px;
text-align: center;
line-height: 40px;
cursor: pointer;
}

:host(:hover) {
border-color: blue;
}

.slotBox {
color: red;
}
</style>
<div class="slotBox">
<slot name="text" class=".slotText">默认的slot展示</slot>
</div>
</template>
<script>
const config = {
// ...
funcs: {
whenClick() {
console.log('我被点击了');
}
}
// ...
};
const customTemplate = (function (config) {
return class extends HTMLElement {
// 监听可以更新的属性
static get observedAttributes() {
return ['click-fnname'];
}
constructor() {
super();
this._clickFnname = () => {
console.log('默认点击事件');
}
// this 就是当前这个自定义的标签
this.template = document.querySelector('.template');
this.shadow = this.attachShadow({
mode: 'open'
})
// 添加template到shadow dom
this.shadow.appendChild(document.importNode(this.template.content, true))
}
// 当被添加的时候会被触发
connectedCallback() {
console.log('调用了');
this.addEventListener('click', this._clickFnname)
}
// 接绑的时候调用
disconnectedCallback() {
console.log('disconnectedCallback');

}
// 自定义标签属性改变时触发
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case 'click-fnname':
// 获取全局下的事件
this._clickFnname = config.funcs[newValue];
break;
default:
break;
}
}
}
})(config);
customElements.define('my-btn', customTemplate);

</script>
</body>

</html>

参考链接: 英文 | 中文 | 一些例子