最近在學(xué)習(xí)polymer ,我根據(jù)自己的所學(xué)給大家寫了一篇polymer 學(xué)習(xí)教程。我們結(jié)合實(shí)例講解,下面手動(dòng)來(lái)創(chuàng)建一個(gè)干凈的項(xiàng)目。
1、cd nodejs
2、mkdir polymer-demo1
3、cd polymer-demo1
4、bower init (一路回車)
5、echo>.bowerrc
{ "directory": "bower_components"}
打開“.bowerrc”文件增加bower安裝組件路徑
6、bower install -save polymer
7、根目錄創(chuàng)建index.html文件
<!DOCTYPE html><html><head>
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<meta charset="UTF-8">
<title>Document</title>
<link rel="import" href="my-elem.html"></head><body>
<my-elem></my-elem></body></html>
8、自定義一個(gè)polymer元素my-elem.html
<link rel="import" href="bower_components/polymer/polymer.html">
<dom-module id="my-elem">
<template>
<h3>my elem test</h3>
</template>
<script>
Polymer({
is: "my-elem",
});
</script></dom-module>
9、安裝 polyserve
npm install -g polyserve
安裝完,啟動(dòng)服務(wù)
polyserve
10、訪問(wèn)
http://localhost:8080/
第一個(gè)簡(jiǎn)單的polymer自定義元素完成!
11、為元素增加、樣式、屬性、監(jiān)聽事件
<link rel="import" href="bower_components/polymer/polymer.html"><dom-module id="my-elem">
<template>
<style>
:host {display: block;}
h3 {color: red;}
h3>span {color: blue;}
</style>
<h3>my <span>elem</span> test</h3>
<p>{{text}}</p>
</template>
<script>
Polymer({
is: "my-elem",
properties: {
text: {
type: String,
value: 'default value'
}
},
listeners: {
'tap': 'click'
},
click: function() {
this.text = "click!";
},
});
</script></dom-module>
<!DOCTYPE html><html><head>
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<meta charset="UTF-8">
<title>Document</title>
<link rel="import" href="my-elem.html"></head><body>
<h3>hello</h3>
<my-elem text='12345689'></my-elem>
<my-elem></my-elem></body></html>
樣式定義放在 template 標(biāo)簽里面
:host 就是當(dāng)前模塊 #my-elem
原文來(lái)自:開源中國(guó)