Web Component
在介绍Angular Component之前,我们先简单了解下W3C Web Components
定义
W3C为统一组件化标准方式,提出Web Component的标准。
每个组件包含自己的html、css、js代码。
Web Component标准包括以下四个重要的概念:
1.Custom Elements(自定义标签):可以创建自定义 HTML 标记和元素;
2.HTML Templates(HTML模版):使用 <template> 标签去预定义一些内容,但并不加载至页面,而是使用 JS 代码去初始化它;
3.Shadow DOM(虚拟DOM):可以创建完全独立与其他元素的DOM子树;
4.HTML Imports(HTML导入):一种在 HTML 文档中引入其他 HTML 文档的方法,<link rel="import" href="example.html" rel="external nofollow" />。
概括来说就是,可以创建自定义标签来引入组件是前端组件化的基础,在页面引用 HTML 文件和 HTML 模板是用于支撑编写组件视图和组件资源管理,而 Shadow DOM 则是隔离组件间代码的冲突和影响。
示例
定义hello-component
<template id="hello-template"> <style> h1 { color: red; } </style> <h1>Hello Web Component!</h1></template><script> // 指向导入文档,即本例的index.html var indexDoc = document; // 指向被导入文档,即当前文档hello.html var helloDoc = (indexDoc._currentScript || indexDoc.currentScript).ownerDocument; // 获得上面的模板 var tmpl = helloDoc.querySelector('#hello-template'); // 创建一个新元素的原型,继承自HTMLElement var HelloProto = Object.create(HTMLElement.prototype); // 设置 Shadow DOM 并将模板的内容克隆进去 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> <!--导入自定义组件--> <link rel="import" href="hello.html" rel="external nofollow" ></head><body> <!--自定义标签--> <hello-component></hello-component></body></html>
从以上代码可看到,hello.html 为按标准定义的组件(名称为 hello-component ),在这个组件中有自己的结构、样式及逻辑,然后在 index.html 中引入该组件文件,即可像普通标签一样使用。
Angular Component
新闻热点
疑难解答
图片精选