8. 组件
8.1 注册组件
组件的data要用函数形式
<div id='app'>
<component1></component1>
<component2></component2>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script>
Vue.component('component2', {
data:function(){
return {
data2:'我是全局注册的数据',
}
},
template:'<div>{{data2}}</div>',
})
var app = new Vue({
el:'#app',
components: {
component1:{
data:function(){
return {
data1:'我是局部注册的数据'
}
},
template:'<div>{{data1}}</div>'
}
}
})
</script>
8.2 父给子组件通信
传递静态props
<div id='app'>
<my-component title='父组件向子组件传递数据'></my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script>
Vue.component('my-component', {
props: ['title'],
template:'<div>{{title}}</div>',
})
var app = new Vue({
el:'#app',
})
</script>
传递动态props
<div id='app'>
<my-component v-bind:title='msg'></my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script>
Vue.component('my-component', {
props: ['title'],
template:'<div>{{title}}</div>',
})
var app = new Vue({
el:'#app',
data:{
msg: '父组件向子组件传递数据'
}
})
</script>
8.3 子给父组件通信
<div id='app'>
<div>{{tip}}</div>
<my-component v-on:aaa=title></my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script>
Vue.component('my-component', {
template:'<button @click=trans>点我</button>',
data () {
return {
msg: '子组件向父组件传递数据 '
}
},
methods:{
trans:function(){
this.$emit('aaa',this.msg)
}
}
})
var app = new Vue({
el:'#app',
data:{
tip:'父组件:'
},
methods: {
title:function(value){
this.tip = this.tip + value
}
}
})
</script>
8.4 同级组件通信
<div id='app'>
<component1></component1>
<component2></component2>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script>
Vue.component('component1', {
template:'<button @click=trans>组件1:点我传递数据</button>',
data () {
return {
msg: '子组件向父组件传递数据 '
}
},
methods:{
trans:function(){
this.$root.bus.$emit('aaa',this.msg)
}
}
})
Vue.component('component2', {
template:'<div>{{title}}</div>',
data () {
return {
title: '组件2:'
}
},
mounted () {
this.$root.bus.$on('aaa',(value)=>{this.title += value})
}
})
var app = new Vue({
el:'#app',
data:{
bus:new Vue()
}
})
8.5 插槽
8.5.1 插槽内容
<div id='app'>
<my-component>插槽里的显示内容</my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script>
Vue.component('my-component', {
template:'<div><p>普通的内容</p><slot>如果组件标签间的内容为空,我就显示<slot></div>',
})
var app = new Vue({
el:'#app',
})
</script>
8.5.2 具名插槽
8.5.3 作用域插槽
8.5.4 访问slot
网友评论