用Custom Element来实现UI组件
用Custom Element來實(shí)現(xiàn)UI組件
最近在做的項(xiàng)目是要用web component的技術(shù)來搭建一個(gè)UI庫。由于之前從來沒接觸過前端的知識(shí),也是趁這次機(jī)會(huì)簡單的學(xué)習(xí)了解了Javascript, HTML, CSS。
Web compoenents 是在當(dāng)前的web 標(biāo)準(zhǔn)下,允許你創(chuàng)建可重用的定制元素并且在web應(yīng)用中使用它。和React, Angular框架下的前端組件不同的是,用web component來創(chuàng)建的定制元素是可以在不同的框架中使用,也可以在html里直接使用,因?yàn)樗臀覀兪褂玫膁iv沒什么區(qū)別,能使用div的地方就能使用它。
Web component是一個(gè)web組件標(biāo)準(zhǔn),由四項(xiàng)技術(shù)組成,分別是Custom elements(自定義元素), Shadow DOM(影子DOM), HTML templates(HTML模版), 和HTML Imports(HTML導(dǎo)入)。 在這里我主要是用了Custom elements來創(chuàng)建和封裝元素。
創(chuàng)建Custom Elements
Web compoenens提供了一系列的生命周期回調(diào)方法, 包括connectedCallback, disconnectedCallback, adoptedCallback,attributeChangedCallback。 以下代碼就是一個(gè)簡單的自定義元素
class MyElements extends HTMLElements {// called when element createdconstructor() {super();//方法在整個(gè)生命周期中只會(huì)被觸發(fā)一次??梢栽谶@里初始化一些變量}// 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() {//當(dāng)組件被加到DOM上,或者節(jié)點(diǎn)在節(jié)點(diǎn)樹中移動(dòng)是,會(huì)被觸發(fā)。}// called when the element is removed from the DOMdisconnectedCallback() {//當(dāng)組件被從DOM上移除時(shí)觸發(fā)。如果在connectedCallback中監(jiān)聽了事件,就一定要在這里把它移出}// called when attribute changedattributeChangedCallback(name, oldValue, newValue) {//當(dāng)組件的attribute改變時(shí),會(huì)被觸發(fā)}} //注冊(cè)自定義組件 window.customElement.define('my-element', MyElement);當(dāng)你的自定義組件創(chuàng)建完后,用customElemnt.define('my-element', MyElement) 來注冊(cè)你的自定義組件。有些舊版本的瀏覽器不支持Web Component, 你需要引入web component規(guī)范的polyfill集合來支持這些功能。Web component提供了 WebComponentsReady的事件來通知你web components是否ready。 所以當(dāng)注冊(cè)自定義組件時(shí),可以用以下代碼來確保瀏覽器擁有了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>) }總結(jié)
個(gè)人覺得web component還是挺好用的,特別喜歡它的就是不會(huì)被框架所限制。使用這個(gè)UI庫的人,不管他是什么技術(shù)棧的,都可以來使用你的UI組件。我目前只接觸了custom element,希望有機(jī)會(huì)可以用到其他的web component的技術(shù)。
總結(jié)
以上是生活随笔為你收集整理的用Custom Element来实现UI组件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CMake I add_custom_c
- 下一篇: custom_filter