## 兄弟组件间通信(event)

借助于一个公共的Vue的实例对象,不同的组件可以通过该对象完成事件的绑定和触发

1
2
3
4
var bus = new Vue();

bus.$emit()
bus.$on()

熊大想要发消息给熊二

接收方(熊二):事件绑定

1
2
3
bus.$on('customEvent',function(msg){
//msg就是通过事件 传递来的数据
})

发送方(熊大):触发事件

1
bus.$emit('customEvent',123);

Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="container">
<p>{{msg}}</p>
<xiongda></xiongda>
<hr>
<xionger></xionger>
</div>
<script>
/*借助于一个公共的Vue的实例对象,不同的组件可以通过该对象完成事件的绑定和触发*/
//new一个对象,兄弟间的通信,将借助他事件绑定和触发来实现
var bus = new Vue();
//熊大发送消息给熊二
//xiongda组件
Vue.component("xiongda",{
data:function(){
return {
xiongDaInput:""
}
},
methods:{
sendToXiongEr:function(){
//给熊二发送消息
//触发msgToXiongEr事件
bus.$emit("msgToXiongEr",this.xiongDaInput);
this.xiongDaInput = "";
}
},
template:`
<div>
<h1>我是熊大</h1>
<input type="text" v-model="xiongDaInput"/>
<button @click="sendToXiongEr">Click Me</button>
</div>
`
})
//熊二组件
Vue.component("xionger",{
data:function(){
return{
recvMsgIs:[]
}
},
template:`
<div>
<h1>我是熊二</h1>
<p v-for="tmp in recvMsgIs">{{tmp}}</p>
</div>
`,
mounted:function(){
// 给该组件绑定一个自定义事件和对应的处理函数
//调用bus中的on方法
//事件的触发一般是接收数据然后处理
var that = this;
bus.$on("msgToXiongEr",function(msg){
//alert("自定义的事件触发,接收到的数据"+msg);
that.recvMsgIs.push(msg);
})
}
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs"
}
})
</script>
</body>
</html>

效果图

在这里插入图片描述