国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

剖析Angular Component的源碼示例

2024-05-06 15:20:26
字體:
供稿:網(wǎng)友

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 江源县| 滦南县| 奈曼旗| 峨山| 北安市| 中牟县| 会同县| 铁岭市| 黄大仙区| 定结县| 神池县| 铜山县| 滦南县| 墨脱县| 南开区| 尼木县| 仲巴县| 霍邱县| 白城市| 连平县| 新安县| 山丹县| 神池县| 定陶县| 延庆县| 句容市| 兴义市| 安康市| 开原市| 灌云县| 东源县| 武功县| 沧州市| 台东县| 墨江| 威海市| 苗栗县| 阿巴嘎旗| 三原县| 连南| 庆阳市|