Angular开发实践(三):剖析Angular Component

在介绍Angular Component之前,我们先简单了解下W3C Web Components

定义

W3C为统一组件化标准方式,提出Web Component的标准。

每个组件包含自己的html、css、js代码。

Web Component标准包括以下四个重要的概念:

Custom Elements(自定义标签):可以创建自定义 HTML 标记和元素;

HTML Templates(HTML模版):使用

概括来说就是,可以创建自定义标签来引入组件是前端组件化的基础,在页面引用 HTML 文件和 HTML 模板是用于支撑编写组件视图和组件资源管理,而 Shadow DOM 则是隔离组件间代码的冲突和影响。

示例

定义hello-component

<template id=http://www.likecs.com/"hello-template"> <style> h1 { color: red; } </style> <h1>Hello Web Component!</h1> </template> <script> // 指向导入文档,即本例的index.html var indexDoc =http://www.likecs.com/ document; // 指向被导入文档,即当前文档hello.html var helloDoc =http://www.likecs.com/ (indexDoc._currentScript || indexDoc.currentScript).ownerDocument; // 获得上面的模板 var tmpl =http://www.likecs.com/ helloDoc.querySelector('#hello-template'); // 创建一个新元素的原型,继承自HTMLElement var HelloProto =http://www.likecs.com/ Object.create(HTMLElement.prototype); // 设置 Shadow DOM 并将模板的内容克隆进去 HelloProto.createdCallback =http://www.likecs.com/ function() { var root =http://www.likecs.com/ this.createShadowRoot(); root.appendChild(indexDoc.importNode(tmpl.content, true)); }; // 注册新元素 var hello =http://www.likecs.com/ indexDoc.registerElement('hello-component', { prototype: HelloProto }); </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpjdss.html