VUE入门-平行兄弟组件之间的通信
By:Roy.LiuLast updated:2020-09-17
VUE组件化开发,不可避免的用到组件之间的通信,最常用的有两种情况, 一是平行的兄弟节点之间的通信,二是父子节点之间的通信,先记录兄弟节点之间的通信处理方式。
VUE兄弟节点之间主要采用注册一个bus消息总线方式来通信,说通俗一点,这个bus就是一个通道,也就是一个 new Vue() 对象,利用这个bus通道,我们可以触发消息或者监听消息, 常用的处理方式如下:
bus=new Vue()//在vue上面挂载一个bus作为消息通道组件
bus.$emit('自定义事件名','传递的数据')//触发自定义事件传递数据
bus.$on('自定义事件名',fn)//监听自定义事件获取数据下面是一个例子,在两个组件之间相互触发事件,监听事件,本例子中监听事件是写在created()方法中的:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue.js"></script>
<style type="text/css">
div {
border:1px solid #ccc;
margin:10px 10px;
line-height: 30px;
}
</style>
</head>
<body>
<div id="app"></div>
<script>
var bus=new Vue();
var BrotherComponentOne = {
template:`
<div>
this is the bro1 component! <br />
<font color=red>{{msg}}</font> <br />
<button v-on:click="sendToBro2">send message to bro2</button>
</div>
`,
data:function() {
return {
msg:"bro1 original msg"
}
},
methods:{
sendToBro2:function(){
bus.$emit('changeBro2Msg','This message is from brother component 1');
}
},
created(){
var self=this;
bus.$on('changeBro1Msg',function(val){
self.msg=val;
})
}
};
var BrotherComponentTwo = {
template:`
<div>
this is the bro2 component! <br/>
<font color=red>{{msg}}</font> <br />
<button v-on:click="sendToBro1">send message to bro1</button>
</div>
`,
data:function(){
return {
msg:"bro2 original message"
}
},
methods:{
sendToBro1:function(){
bus.$emit('changeBro1Msg','This message is from bro2');
}
},
created(){
var self=this;
bus.$on('changeBro2Msg',function(val){
self.msg=val;
})
}
};
new Vue({
el:"#app",
template:`
<div>
<BrotherComponentOne></BrotherComponentOne>
<BrotherComponentTwo></BrotherComponentTwo>
</div>
`,
data:function(){
return {
}
},
components:{
BrotherComponentOne,BrotherComponentTwo
}
})
</script>
</body>
</html>From:一号门
Previous:VUE入门-组件化开发
Next:VUE入门-父子组件之间的通信

COMMENTS