本系列主要翻譯官方的教程,因為國內目前這方面的資料太少了,但也不一定和官網的一樣,反正就是自己想到哪就寫到哪。
如果我沒有說明,默認情況下index.html始終包含這段代碼,后面將不會再貼上來。
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- 這是一個基礎版的兼容庫 -->
<script src="webcomponents-lite.min.js"></script>
<!-- 將rel修改為import可以引入另外一個HTML,它將會被執行 -->
<link rel="import" href="./template/template.html">
</head>
template.html始終包含
<link rel="import" href="../polymer-1.7.0/polymer.html">
我們可以創建一個自定義元素,並向這個自定義元素添加屬性和方法,不過值得注意的是:自定義元素的名稱必須包含一個“-”。
template.html
<script>
Polymer({
is: "proto-element",
ready: function() {
this.textContent = "I'm a proto-element. Check out my prototype!"
}
});
</script>
is:創建一個自定義元素,必須包含“-”,也就是你要的標簽名。
ready:當在頁面中創建了proto-element
這個元素后將會調到這個方法,this
表示當前這個元素,this.textContent
設置內容。
index.html
<proto-element></proto-element>
就是用is定義的那個名字
效果
添加本地DOM
template.html
<dom-module id="dom-element">
<template>
<p>I'm a DOM element. This is my local DOM!</p>
</template>
<script>
Polymer({
is: "dom-element"
});
</script>
</dom-module>
用dom-module來添加原生dom,如果用這種方式需要給它加一個id使用的時候就用這個id當做標簽名。
template用來包含css、html
index.html
<dom-element></dom-element>
效果:
與原生DOM結合
template.html
<dom-module id="picture-frame">
<template>
<style>
div {
display: inline-block;
background-color: #ccc;
border-radius: 8px;
padding: 4px;
}
</style>
<div>
<content></content>
</div>
</template>
<script>
Polymer({
is: "picture-frame",
});
</script>
</dom-module>
如果希望在自定義組件中插入內容就需要用到content
標簽,它會將我們寫的標簽插入到content
中。
index.html
<picture-frame>
<p>聽說你要學前端。</p>
</picture-frame>
效果
提示:將style放在template中,它之會影響template里面的元素。
數據綁定
template.html
<dom-module id="name-tag">
<template>
<!-- 將owner綁定到property上 -->
This is <b>{{owner}}</b>'s name-tag element.
</template>
<script>
Polymer({
is: "name-tag",
// 當元素准備好的時候將owner屬性的值設置為"Daniel"
ready: function() {
this.owner = "Daniel";
}
});
</script>
</dom-module>
index.html
<name-tag></name-tag>
聲明一個屬性
template.html
<dom-module id="configurable-name-tag">
<template>
This is <b>{{owner}}</b>'s configurable-name-tag element.
</template>
<script>
Polymer({
is: "configurable-name-tag",
properties: {
owner: {
type: String,
value: "Daniel"
}
}
});
</script>
</dom-module>
通過properties聲明一個自定義屬性,type屬性類型,value屬性默認內容(如果自定義元素沒有寫這個屬性的話)。
index.html
<configurable-name-tag owner="Scott"></configurable-name-tag>
效果
雙向數據綁定
template.html
<link rel="import" href="https://polygit2.appspot.com/components/iron-input/iron-input.html">
<dom-module id="editable-name-tag">
<template>
<p>
This is a <strong>{{owner}}</strong>'s editable-name-tag.
</p>
<!-- iron-input exposes a two-way bindable input value -->
<input is="iron-input" bind-value="{{owner}}" placeholder="Your name here...">
</template>
<script>
Polymer({
is: "editable-name-tag",
properties: {
owner: {
type: String,
value: "Daniel"
}
}
});
</script>
</dom-module>
注意這里不要把polymer.html引進來,iron-input.html是一個對input的擴展庫。
index.html
<editable-name-tag></editable-name-tag>
效果
本節完,后面會更加詳細的介紹,但是本人也是剛剛接觸這個,難免有解釋不太清楚的,還請見諒。