什么是組件?
組件是自定義元素蚁吝。比如html沒(méi)有 <simple-counter></simple-counter>這個(gè)標(biāo)簽旱爆,我們可以創(chuàng)建一個(gè)。在vue里叫做組件
全局組件和局部組件
全劇組件窘茁。
就是用Vue.component()這種方法注冊(cè)的組件
比如
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<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:function(){
return {
message:'good'
}
}
})
new Vue({
el: '#example-2'
})
</script>
局部組件
不必在全局注冊(cè)每個(gè)組件怀伦。通過(guò)使用組件實(shí)例選項(xiàng)注冊(cè),可以使組件僅在另一個(gè)實(shí)例/組件的作用域中可用:
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="example-2">
<simple-counter></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>
</div>
</div>
<script>
var xx = {
template:'<h1>{{message}}</h1>',
data:function(){
return {
message:'good'
}
}
}
new Vue({
el: '#example-2',
components:{
'simple-counter':xx
},
})
</script>
當(dāng)然這么寫(xiě)也可以
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="example-2">
<simple-counter></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>
</div>
</div>
<script>
new Vue({
el: '#example-2',
components:{
'simple-counter':{
template:'<h1>{{message}}</h1>',
data:function(){
return {
message:'good'
}
}
}
},
})
</script>
組件通信山林?
子組件不能直接利用父組件的數(shù)據(jù)房待。比如下面這個(gè),message="good"是在父組件(就是simple-counter里)里的驼抹,沒(méi)法傳遞到子組件(就是h1標(biāo)簽里)桑孩。結(jié)果什么也沒(méi)渲染出來(lái)。
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="example-2">
<simple-counter message="good"></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>
</div>
</div>
<script>
Vue.component('simple-counter', {
template: '<h1>{{message}}</h1>',
})
new Vue({
el: '#example-2'
})
</script>
加上一句
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="example-2">
<simple-counter message="good"></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>
</div>
</div>
<script>
Vue.component('simple-counter', {
props:['message'],
template: '<h1>{{message}}</h1>',
})
new Vue({
el: '#example-2'
})
</script>
結(jié)果
傳遞多個(gè)數(shù)據(jù)
<div id="example-2">
<simple-counter message="good"></simple-counter>
<simple-counter size='apple'></simple-counter>
<simple-counter></simple-counter>
</div>
</div>
<script>
Vue.component('simple-counter', {
props:['message','size'],
template: '<h1>{{message}} {{size}}</h1>',
})
new Vue({
el: '#example-2'
})
</script>