Home > Article > Web Front-end > Communication between peers of Vue.js components (code)
This article introduces Vue.jsCommunication (code) between peers of components
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>componentKnowledge-同级组件通信</title> <script src="js/vue.js"></script> </head> <body> <template id="aa"> <p> I am aa component:{{msg}} <input type="button" @click="send" value="SendTo-cc"> </p> </template> <template id="bb"> <p> I am bb component:{{msg}} <input type="button" @click="send" value="SendTo-cc"> </p> </template> <template id="cc"> <p> <p> I am cc component:{{msg}}/receive data:{{msg2}},{{msg3}} </p> </p> </template> <script> window.onload=function(){ let Event=new Vue(); let aa={//定义组件 template:'#aa', data(){ return {msg:'aa data'} }, methods:{ send(){ Event.$emit('a-send',this.msg) } } }; let bb={//定义组件 template:'#bb', data(){ return {msg:'bb data'} }, methods:{ send(){ Event.$emit('b-send',this.msg) } } }; let cc={//定义组件 template:'#cc', data(){ return { msg:'cc data', msg2:'', msg3:'' } }, mounted(){ Event.$on('a-send',(data)=>{this.msg2=data}); Event.$on('b-send',(data)=>{this.msg3=data}); } }; let vm=new Vue({ el:'#app', components:{//注册组件 aa, bb, cc } }); } /*同级组件之间的通信关键总结: 1:新建一个空的root组件:let Event=new Vue(); 其上有两个方法Event.$emit('a-fnName',data)/Event.$on('a-fnName',(data)=>{}) 2:发送数据的组件:Event.$emit('a-fnName',data)写在组件的methods里, 3:接收数据的组件:Event.$on('a-fnName',(data)=>{}),注意函数格式必须写为箭头函数,不然this指向不是当前组件,一般写在钩子函数里(beforeCreate(){}/created(){}/beforeMount(){}/Mounted(){}/beforeUpdate(){}/updated(){}/beforeDestroy(){}/destroyed(){}) */ </script> <p id="app"> <!--使用组件--> <aa></aa> <bb></bb> <cc></cc> </p> </body> </html>
The above is the detailed content of Communication between peers of Vue.js components (code). For more information, please follow other related articles on the PHP Chinese website!