Web Components
Web Components
Web Components标题标准非常重要的一个特性是,它使开发者能够将HTML页面的功能封装为 custom elements(自定义标签),而往常,开发者不得不写一大堆冗长、深层嵌套的标签来实现同样的页面功能。这篇文章将会介绍如何使用HTML的custom elements;目前angular框架内以支持将动态组件通过webComponents的形式嵌入到视图中;具体可参考angular教程地址
1.customElements
customElements就是浏览器暴露给我们的API,方法define()可以直接定义一个自定义元素,这个元素继承自HTMLElement,具有html元素的一切属性和方法。
2.用法
customElements.define('custom-ele', classConstuctor, { extends: 'div' });
第一个参数就是我们自定义元素的名称;第二个参数类似于我们常用框架中的组件构造函数,具有自己的生命周期;第三个参数可选:例如extends表示继承自div元素。
3 用例讲解
class PopUp extends HTMLElement {
constructor () {
const d = super();
console.log(d, this);
const shadow = d.attachShadow({mode: 'open'});
const wrapper = document.createElement('span');
wrapper.setAttribute('class', 'wrapper');
const span = document.createElement('span');
span.innerHTML = 'hover me';
const pop = document.createElement('span');
pop.innerHTML = d.dataset.text;
span.classList.toggle('poped');
const style = document.createElement('style');
console.log(style.isConnected);
style.textContent = `
.wrapper {
position: relative;
}
.poped+span {
font-size: 0.8rem;
width: 200px;
display: inline-block;
border: 1px solid black;
padding: 10px;
background: white;
border-radius: 10px;
opacity: 0;
transition: 0.6s all;
position: absolute;
bottom: 20px;
left: 10px;
z-index: 3;
}
img {
width: 1.2rem;
}
.poped:hover + span, .poped:focus + span {
opacity: 1;
}
`;
// Attach the created elements to the shadow dom
shadow.appendChild(style);
wrapper.appendChild(span);
wrapper.appendChild(pop);
shadow.appendChild(wrapper);
setInterval(() => {
this.setAttribute('l', Math.random())
}, 2000)
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(name, oldValue, newValue, 'updated');
}
connectedCallback(e) {
console.log(e, 'connected')
}
static get observedAttributes(){
return ['l']
}
}
customElements.define('popup-info', PopUp)
这里我们利用MDN上的例子进行举例
PopUp是一个弹出框组件
- 我们的视图选择浏览器原生的 Shadow DOM;这样我们添加的样式就会只在这个shadow中起作用;
- 我们需要定义的属性可以调用dom操作来添加,也可以通过构造函数的this手动指定;比如我们需要为custom-ele添加id,那么只需要在constructor中这样this.id='id’就可以了;
- 元素的tagName必须有短横线,不能是单个单词;
- 通过DOM三级事件按,我们同样也可以为元素添加我们需要添加的事件,事件的监听方法相同;
- 生命周期:
【1】connectedCallback:当 custom element首次被插入文档DOM时, 被调用。
【2】disconnectedCallback:当 custom element从文档DOM中删除时,被调用。
【3】adoptedCallback:当 custom element被移动到新的文档时,被调用。
【4】attributeChangedCallback: 当 custom element增加、删除、修改自身属性时,被调用
如例子中所示:我们在构造函数中设置了定时器,不断更改其属性,对应的属性变化回调就会一直执行。
注:并不是所有的属性都会被监听:只有被添加的属性会被监听到需要添加静态方法get observedAttributes(){return attr[];}才能够监听到。
static get observedAttributes(){
return ['l']
}
简单汇总
这里只是介绍了customElement自定义元素的用法,在框架中,基本都已提供了自定义元素渲染组件的方法;如何写出高效可复用的web组件还是取决于自己的经验。
注意:在ts中,需要引用polyfill:
import‘@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js’