Web Component
在介紹Angular Component之前,我們先簡單了解下W3C Web Components
定義
W3C為統(tǒng)一組件化標(biāo)準(zhǔn)方式,提出Web Component的標(biāo)準(zhǔn)。
每個(gè)組件包含自己的html、css、js代碼。
Web Component標(biāo)準(zhǔn)包括以下四個(gè)重要的概念:
1.Custom Elements(自定義標(biāo)簽):可以創(chuàng)建自定義 HTML 標(biāo)記和元素;
2.HTML Templates(HTML模版):使用 <template> 標(biāo)簽去預(yù)定義一些內(nèi)容,但并不加載至頁面,而是使用 JS 代碼去初始化它;
3.Shadow DOM(虛擬DOM):可以創(chuàng)建完全獨(dú)立與其他元素的DOM子樹;
4.HTML Imports(HTML導(dǎo)入):一種在 HTML 文檔中引入其他 HTML 文檔的方法,<link rel="import" href="example.html" rel="external nofollow" />。
概括來說就是,可以創(chuàng)建自定義標(biāo)簽來引入組件是前端組件化的基礎(chǔ),在頁面引用 HTML 文件和 HTML 模板是用于支撐編寫組件視圖和組件資源管理,而 Shadow DOM 則是隔離組件間代碼的沖突和影響。
示例
定義hello-component
<template id="hello-template"> <style> h1 { color: red; } </style> <h1>Hello Web Component!</h1></template><script> // 指向?qū)胛臋n,即本例的index.html var indexDoc = document; // 指向被導(dǎo)入文檔,即當(dāng)前文檔hello.html var helloDoc = (indexDoc._currentScript || indexDoc.currentScript).ownerDocument; // 獲得上面的模板 var tmpl = helloDoc.querySelector('#hello-template'); // 創(chuàng)建一個(gè)新元素的原型,繼承自HTMLElement var HelloProto = Object.create(HTMLElement.prototype); // 設(shè)置 Shadow DOM 并將模板的內(nèi)容克隆進(jìn)去 HelloProto.createdCallback = function() { var root = this.createShadowRoot(); root.appendChild(indexDoc.importNode(tmpl.content, true)); }; // 注冊新元素 var hello = indexDoc.registerElement('hello-component', { prototype: HelloProto });</script>使用hello-component
<!DOCTYPE html><html lang="zh-cn"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="author" content="賴祥燃, laixiangran@163.com, http://www.laixiangran.cn"/> <title>Web Component</title> <!--導(dǎo)入自定義組件--> <link rel="import" href="hello.html" rel="external nofollow" ></head><body> <!--自定義標(biāo)簽--> <hello-component></hello-component></body></html>
從以上代碼可看到,hello.html 為按標(biāo)準(zhǔn)定義的組件(名稱為 hello-component ),在這個(gè)組件中有自己的結(jié)構(gòu)、樣式及邏輯,然后在 index.html 中引入該組件文件,即可像普通標(biāo)簽一樣使用。
Angular Component
新聞熱點(diǎn)
疑難解答
圖片精選