什么是组件?
组件是自定义元素。比如html没有 <simple-counter></simple-counter>这个标签,我们可以创建一个。在vue里叫做组件
全局组件和局部组件
全剧组件。
就是用Vue.component()这种方法注册的组件
比如
<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>
局部组件
不必在全局注册每个组件。通过使用组件实例选项注册,可以使组件仅在另一个实例/组件的作用域中可用:
<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>
当然这么写也可以
<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>
组件通信?
子组件不能直接利用父组件的数据。比如下面这个,message="good"是在父组件(就是simple-counter里)里的,没法传递到子组件(就是h1标签里)。结果什么也没渲染出来。
<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>
结果
传递多个数据
<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>