基本示例
// 定義一個(gè)名為 button-counter 的新組件
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
<div id="components-demo">
<button-counter></button-counter>
</div>
new Vue({ el: '#components-demo' })
所謂的組件,其實(shí)就是個(gè)小的vue實(shí)例,只不過換了個(gè)名字,所以vue帶有的data,methods,computed,生命周期鉤子等等它都會(huì)有。
組件復(fù)用
組件可以任意次數(shù)的復(fù)用,其數(shù)據(jù)和方法相互獨(dú)立。
注意:data的寫法和vue的不一樣,它必須是個(gè)函數(shù),這個(gè)寫法保證了組件的數(shù)據(jù)是相互獨(dú)立的。
通過prop向子組件傳遞數(shù)據(jù)
<blog-post title="Why Vue is so fun"></blog-post>
Vue.component('blog-post', {
props: ['title'],
template: '<h3>{{ title }}</h3>'
})
不一定非傳遞一個(gè)需要的值,你可以將這個(gè)子組件所有的屬性打包成一個(gè)對象傳遞過去,這樣子組件需要新的參數(shù)的時(shí)候就不需要去修改組件代碼,而是直接使用.XXX獲得值:
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
></blog-post>
Vue.component('blog-post', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content"></div>
</div>
`
})
子組件拋出事件
// 組件標(biāo)簽上寫上on,來監(jiān)聽特定的事件
<blog-post
...
v-on:enlarge-text="postFontSize += 0.1"
></blog-post>
// 子組件自身在拋出事件即可監(jiān)聽
<button v-on:click="$emit('enlarge-text')">
Enlarge text
</button>
// 當(dāng)然也可以帶上值
<button v-on:click="$emit('enlarge-text', 0.1)">
Enlarge text
</button>