用Custom Element来实现UI组件
用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 createdconstructor() {super();//方法在整個生命周期中只會被觸發一次。可以在這里初始化一些變量}// return an array of the attribute names you want to watch for changesobservedAttributes() {// 在這里返回自定義元素的屬性return ['label'];}get label() {this.getAttribute('label') || '';}set label(value) {this.setAttribute('label', value);}// called when the element is added to the DOMconnectedCallback() {//當組件被加到DOM上,或者節點在節點樹中移動是,會被觸發。}// called when the element is removed from the DOMdisconnectedCallback() {//當組件被從DOM上移除時觸發。如果在connectedCallback中監聽了事件,就一定要在這里把它移出}// called when attribute changedattributeChangedCallback(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的技術。
總結
以上是生活随笔為你收集整理的用Custom Element来实现UI组件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CMake I add_custom_c
- 下一篇: custom_filter