什么是組件淘邻?
組件(Component)是 Vue.js 最強大的功能之一菠隆。
組件可以擴展 HTML 元素譬重,封裝可重用的代碼读整。
組件系統(tǒng)讓我們可以用獨立可復用的小組件來構建大型應用簿训,幾乎任意類型的應用的界面都可以抽象為一個組件樹。
實例
首先應該注冊米间,也就是告訴瀏覽器我新發(fā)明了一個元素强品。
要注冊一個全局組件,你可以使用 Vue.component(tagName, options)屈糊。例如:
Vue.component('my-component', {
// 選項
})
舉個例子
假設及擴展了一個叫做hh的標簽
<hh>
</hh>
那么應該如何注冊的榛。首先html文本里得有,然后再去注冊逻锐。利用Vue.component進行注冊夫晌,然后第一個參數(shù)是新創(chuàng)建的標簽名雕薪,第二個標簽時模板或者叫選項。
<style>
.apple {
color:red;
}
</style>
</head>
<body>
<div id="app">
<hh>xx</hh>
</div>
<script>
// 注冊
Vue.component('hh', {
template: '<div class="apple">自定義組件!</div>'
})
// 創(chuàng)建根實例
new Vue({
el: '#app'
})
</script>
結果
image.png
data必須是一個函數(shù)
舉個例子,如下data不是函數(shù)晓淀,結果呢蹦哼?沒有內(nèi)容輸出。
<div id="example-2">
<simple-counter></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>
</div>
</div>
<script>
Vue.component('simple-counter', {
template: '<h1>{{message}}</h1>',
data:{
message:'Hello Vue.js!'
}
})
new Vue({
el: '#example-2'
})
</script>
給script中的內(nèi)容換個寫法
<script>
var x={message:'good'}
Vue.component('simple-counter', {
template: '<h1>{{message}}</h1>',
data:function(){
return x
}
})
new Vue({
el: '#example-2'
})
</script>
結果
image.png
也可以這么寫.不用首先定義x要糊。結果是一樣的纲熏。
<script>
Vue.component('simple-counter', {
template: '<h1>{{message}}</h1>',
data:function(){
return {
message:'good'
}
}
})
new Vue({
el: '#example-2'
})
</script>
總之呢,就是必須把data的內(nèi)容包裹在函數(shù)里锄俄。
可是為什么這么設計呢局劲?
換個例子來說明
<div id="example-2">
<simple-counter></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>
</div>
</div>
<script>
var data = { counter: 0 }
Vue.component('simple-counter', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
// 技術上 data 的確是一個函數(shù)了,因此 Vue 不會警告奶赠,
// 但是我們返回給每個組件的實例的卻引用了同一個data對象
data: function () {
return data
}
})
new Vue({
el: '#example-2'
})
</script>
結果是鱼填。三個按鈕數(shù)值同步變化
image.png
如何讓每個按鈕各自變化呢?
只需要把return的內(nèi)容修改一下
return {
counter:0
}
結果三個按鈕內(nèi)容獨自變化
image.png
最終用function實現(xiàn)了該功能毅戈,可以想象的是苹丸,如果和之前一樣采用鍵值對比較難搞。大致意思如此
未完待續(xù)