VUE入门-平行兄弟组件之间的通信

摘要: VUE组件化开发,不可避免的用到组件之间的通信,最常用的有两种情况, 一是平行的兄弟节点之间的通信,二是父子节点之间的通信,先记录兄弟节点之间的通信处理方式

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>


上一篇: VUE入门-组件化开发
下一篇: VUE入门-父子组件之间的通信
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号