书接上回,咱们已经把运行Polymer的准备工做作好,接下来就敲点代码来感觉下它究竟是个什么东东,这一篇里我基本会照搬官网Quick tour的几个例子来快速过一下。html
须要调用Polymer这个function才能在浏览器中注册一个新的组件,你须要给这个新组件关联一个标签名,你也能够在这个组件上添加你自定义的属性和方法。很是重要的一点是,这个组件的标签名必需要以“-”符号分割。
你须要把这个组件的各类定义封装在一个对象里做为参数传入到Polymer函数中去。web
proto-element.html(自定义组件)segmentfault
<link rel="import" href="bower_components/polymer/polymer.html"> <!-- link rel="import" 这种写法可能比较陌生,其实就是导入一个已经封装好的自定义组件,这里导入了polymer.html你能够打开看一下里面有对Polymer function的定义 --> <script> // register a new element called proto-element Polymer({ is: "proto-element", //is来标示组件的标签名 // add a callback to the element's prototype ready: function() { //ready是组件生命周期的一部分,这块之后会具体开一篇介绍 this.textContent = "I'm a proto-element. Check out my prototype!" //为组件赋上一段文字 } }); </script>
index.html浏览器
<!DOCTYPE html> <html> <head> <script src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="proto-element.html"> <!-- 这里就是导入了上面已经定义好的自定义组件 proto-element --> </head> <body> <proto-element></proto-element><!-- 用标签的形式加载自定义组件--> </body> </html>
运行效果dom
上面这个例子只是将一段text封装成一个组件,在实际使用过程当中咱们不多会这么干,绝大部分状况下咱们封装的最小颗粒都是原生的标签,下面这个例子就对dom进行封装(官网称为local dom)svg
dom-element.html函数
<link rel="import" href="bower_components/polymer/polymer.html"> <dom-module id="dom-element"> <template> <p>I'm a DOM element. This is my local DOM!</p> </template> <!--这里用一个template标签来封装了dom--> <script> Polymer({ is: "dom-element" }); </script> </dom-module><!--最外层也用了dom-module来包裹-->
index.htmlui
<!DOCTYPE html> <html> <head> <script src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="dom-element.html"> </head> <body> <dom-element></dom-element> </body> </html>
运行结果this
这个功能不太好翻译,大概意思就是你能够把一些子组件或者子标签经过标签嵌套的方式插入到父的组件中去,语言可能不太好描述,我们直接用代码说话
picture-frame.htmlspa
<link rel="import" href="bower_components/polymer/polymer.html"> <dom-module id="picture-frame"> <template> <!-- scoped CSS for this element --> <style> div { display: inline-block; background-color: #ccc; border-radius: 8px; padding: 4px; } </style> <div> <!-- any children are rendered here --> <content></content> <!--注意这里使用了content标签,子组件或者标签将被插入到这里--> </div> </template> <script> Polymer({ is: "picture-frame", }); </script> </dom-module>
index.html
<!DOCTYPE html> <html> <head> <script src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="picture-frame.html"> </head> <body> <picture-frame> <img src="images/p-logo.svg"><!--此处就是讲一个原生的img标签做为子组件插入到picture-frame中去--> </picture-frame> </body> </html>
运行结果
hello world的上篇完毕,下篇会继续讲到自定义组件的双向绑定,自定义属性等功能。