組件基礎
一個組件要想重複使用,data值必須設爲函數,函數裏返回對象,這樣才能避免多個組件實例公用一個對象(看需不需要public變量):
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
每個組件只能有一個根元素
//可以註冊成功
<div class="blog-post">
<h3>{{ title }}</h3>
<div v-html="content"></div>
</div>
//註冊會失敗
<h3>{{ title }}</h3>
<div v-html="content"></div>
通過事件向向父機組件發送消息
//組件內的button點擊發送自定義信號
<button v-on:click="$emit('enlarge-text')">
Enlarge text
</button>
//blog-post爲自定義組件
<blog-post
...
v-on:enlarge-text="postFontSize += 0.1"
></blog-post>
//信號傳值
<button v-on:click="$emit('enlarge-text', 0.1)">
Enlarge text
</button>
//通過$event訪問
<blog-post
...
v-on:enlarge-text="postFontSize += $event"
></blog-post>
//用一個方法來接收
<blog-post
...
v-on:enlarge-text="onEnlargeText"
></blog-post>
//vue.component中:
methods: {
onEnlargeText: function (enlargeAmount) {
this.postFontSize += enlargeAmount
}
}