- Vue 如何实现组件通信?
①父组件向子组件通信(props:['属性名']
)
- 给父组件中的子组件标签绑定属性,然后在子组件里通过添加
props:['属性名']
传递数据;
//html
<div id="app" >
<component-A name='hi'></component-A>
</div>
//JS
Vue.component('componentA',{
props:['name'],
template:`
<div class="son">
我的名字是{{name}}
</div>
`
})//子组件一定要注册在父组件前面
new Vue({
el:"#app",
})
![](https://img.haomeiwen.com/i8000597/ad029548da5a994c.png)
②子组件向父组件传递数据(
$emit('事件名',data)
)
- 通过发布订阅模式,子组件通过
$emit('事件名',data)
(data为需要传给父组件的数据)发布事件,父组件(父组件中的子组件标签)监听这个事件,并调用函数
<div id="app" >
{{info}}
<component-A name='hi' @change='changeMe'></component-A>
</div>
//JS
Vue.component('componentA',{
props:['name'],
template:`
<div class="son">
我的名字是{{name}}
<button @click="$emit('change')">传递消息</button>
</div>
`
})
new Vue({
el:"#app",
data:{
info:'暂无消息'
},
methods:{
changeMe:function(){
this.info = '收到'
}
}
})
![](https://img.haomeiwen.com/i8000597/30b7752d001a7e09.png)
![](https://img.haomeiwen.com/i8000597/b864382d6e52d439.png)
③兄弟组件传递数据
-
let eventHub = new Vue()
Vue.prototype.$eventHub = eventHub
声明一个Vue实例,把它加到Vue的原型上,就可以通过$eventHub
来调用$emit,$on
了
<div id="app">
<component-a></component-a>
<component-b></component-b>
</div>
let eventHub = new Vue()
Vue.prototype.$eventHub = eventHub
Vue.component('component-a',{
template:`
<div class="a">A
<button @click='notify'>click</button>
</div>
`,
methods:{
notify:function(){
this.$eventHub.$emit('setB','hello')
}
}
})
Vue.component('component-b',{
template:`
<div class="b">B<div ref=change></div>
</div>
`,
created(){
this.$eventHub.$on('setB',(data)=>{
this.$refs.change.textContent = data
})
}
})
new Vue({
el:"#app"
})
![](https://img.haomeiwen.com/i8000597/a62c1c33a47509db.png)
④爷孙通信
- 爷孙组件之间是不能直接通信的,但可以构造成两个父子组件,通过父组件来传递数据
网友评论