<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> vue父子组件通信、兄弟组件通信</title> <style> *{ margin: 0; padding: 0; list-style: none; } table{ text-align: center; margin:0 auto; } div{ text-align: center; } </style> </head> <body> <div> <table cellpadding="0" cellspacing="0"> <tr><td colspan="3">父组件数据</td></tr> <tr><td>name</td><td>{{name}}{{ff()}}</td><td><input type="text" v-model="name"></td></tr> <tr><td>age</td><td>{{age}}{{ff()}}</td><td><input type="text" v-model="age"></td></tr> </table> <v-son :son-name="name" :son-age="age" @sza="gg"></v-son> </div> <template> <div> <button @click="sonChange">子组件按钮</button> <table cellpadding="0" cellspacing="0"> <tr><td colspan="3">子组件数据</td></tr> <tr><td>name</td><td>{{sonName}}</td><td><input type="text" v-model="sonName"></td></tr> <tr><td>age</td><td>{{sonAge}}</td><td><input type="text" v-model="sonAge"></td></tr> </table> <g-son :g-name="sonName" :g-age="sonAge"></g-son> </div> </template> <template> <div> <button @click="gchan">孙子组件按钮</button> <table cellpadding="0" cellspacing="0"> <tr><td colspan="3">孙子组件数据</td></tr> <tr><td>name</td><td>{{gName}}</td><td><input type="text" v-model="gName"></td></tr> <tr><td>age</td><td>{{gAge}}</td><td><input type="text" v-model="gAge"></td></tr> </table> </div> </template> </body> <script src="https://cdn.bootcss.com/vue/2.4.4/vue.min.js"></script> <script> var bus=new Vue(); const app=new Vue({ el:"#app", data:{ name:"keep", age:"28" }, methods:{ gg(val1,val2){ this.name=val1 this.age=val2 }, ff(){ bus.$on("suibian", (val1,val2)=> { this.name=val1; this.age=val2 }) } }, components:{ "vSon":{ template:"#son", methods:{ sonChange(){ this.$emit("sza",this.sonName,this.sonAge) } }, props:["sonName","sonAge"], components:{ "gSon":{ template:"#vgson", props:["gName","gAge"], methods:{ gchan(){ bus.$emit("suibian",this.gName,this.gAge); }, } } }, } } }) </script> </html>
vue实现父子组件之间的通信以及兄弟组件的通信
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:http://www.heiqu.com/9ea254c872b0e934cbcf4854d1654136.html