用Custom Element来实现UI组件
最近在做的项目是要用web component的技术来搭建一个UI库。由于之前从来没接触过前端的知识,也是趁这次机会简单的学习了解了Javascript, HTML, CSS。
Web compoenents 是在当前的web 标准下,允许你创建可重用的定制元素并且在web应用中使用它。和React, Angular框架下的前端组件不同的是,用web component来创建的定制元素是可以在不同的框架中使用,也可以在html里直接使用,因为他和我们使用的div没什么区别,能使用div的地方就能使用它。
Web component是一个web组件标准,由四项技术组成,分别是Custom elements(自定义元素), Shadow DOM(影子DOM), HTML templates(HTML模版), 和HTML Imports(HTML导入)。 在这里我主要是用了Custom elements来创建和封装元素。
创建Custom Elements
Web compoenens提供了一系列的生命周期回调方法, 包括connectedCallback, disconnectedCallback, adoptedCallback,attributeChangedCallback。 以下代码就是一个简单的自定义元素
class MyElements extends HTMLElements {
// called when element created
constructor() {
super();
//方法在整个生命周期中只会被触发一次。可以在这里初始化一些变量
}
// return an array of the attribute names you want to watch for changes
observedAttributes() {
// 在这里返回自定义元素的属性
return ['label'];
}
get label() {
this.getAttribute('label') || '';
}
set label(value) {
this.setAttribute('label', value);
}
// called when the element is added to the DOM
connectedCallback() {
//当组件被加到DOM上,或者节点在节点树中移动是,会被触发。
}
// called when the element is removed from the DOM
disconnectedCallback() {
//当组件被从DOM上移除时触发。如果在connectedCallback中监听了事件,就一定要在这里把它移出
}
// called when attribute changed
attributeChangedCallback(name, oldValue, newValue) {
//当组件的attribute改变时,会被触发
}
}
//注册自定义组件
window.customElement.define('my-element', MyElement);
当你的自定义组件创建完后,用customElemnt.define('my-element', MyElement) 来注册你的自定义组件。有些旧版本的浏览器不支持Web Component, 你需要引入web component规范的polyfill集合来支持这些功能。Web component提供了 WebComponentsReady的事件来通知你web components是否ready。 所以当注册自定义组件时,可以用以下代码来确保浏览器拥有了web compoennt的API。
let defineElement = function() {
if (!window.customElements.get('my-element')) {
window.customElements.define('my-element', MyElement);
}
};
if (window.customElements) {
defineElement();
} else {
document.addEventListener('WebComponentsReady', defineElement);
}
这里是web components pollyfill的GitHub地址: https://github.com/webcomponents/webcomponentsjs
使用Custom Element
你可以直接在HTML文件中使用,比如
<my-element></my-element>
值得注意的是,如果你在html中使用你的自定义tag,你必须要把 写上。
你也可以在React或者其他框架下中使用, 比如在React中:
render() {
return (
<div>
<my-element label='hello' />
</div>
)
}
总结
个人觉得web component还是挺好用的,特别喜欢它的就是不会被框架所限制。使用这个UI库的人,不管他是什么技术栈的,都可以来使用你的UI组件。我目前只接触了custom element,希望有机会可以用到其他的web component的技术。
本文介绍了如何利用Web Components中的Custom Elements技术创建和封装可重用的UI组件。通过阐述Custom Elements的生命周期回调方法以及如何注册和使用自定义元素,展示了其跨框架的适用性,强调了它在不同技术栈间通用的优势。
663

被折叠的 条评论
为什么被折叠?



