vue实现的组件兄弟间通信功能示例

时间:2021-05-26

本文实例讲述了vue实现的组件兄弟间通信功能。分享给大家供大家参考,具体如下:

兄弟组件间通信(event)

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

var bus = new Vue();bus.$emit()bus.$on()

熊大想要发消息给熊二,

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

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

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

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

练习:

在熊二中 加上一个button,
点击按钮时告诉熊大:'快跑!'

接收方:事件绑定
发送方:触发事件

<!doctype html><html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.bootcss.com/vue/2.0.1/vue.min.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <xiongda></xiongda> <hr> <xionger></xionger> </div> <script>//new一个对象,兄弟间的通信,将借助他事件绑定和触发来实现 var bus = new Vue(); //熊大发送消息给熊二 //xiongda组件 Vue.component("xiongda",{ methods:{ sendToXiongEr:function(){ //给熊二发送消息 //触发msgToXiongEr事件 bus.$emit("msgToXiongEr","哈哈,光头强来了"); } }, template:` <div> <h1>我是熊大</h1> <button @click="sendToXiongEr">Click Me</button> </div> ` })//熊二组件 Vue.component("xionger",{ template:` <div> <h1>我是熊二</h1> </div> `, mounted:function(){// 给该组件绑定一个自定义事件和对应的处理函数 //调用bus中的on方法 //事件的触发一般是接收数据然后处理 var that = this; bus.$on("msgToXiongEr",function(msg){ alert("自定义的事件触发,接收到的数据"+msg); }) } }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body></html>

使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试,可得到如下运行效果:

改版:熊大在input输入数据传递给熊二

<!doctype html><html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.bootcss.com/vue/2.0.1/vue.min.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <xiongda></xiongda> <hr> <xionger></xionger> </div> <script>//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>

感兴趣的朋友还可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码的运行效果。

希望本文所述对大家vue.js程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章