A组件给B组件传数据: A发送数据: var Event_z = new Vue(); Event_z.$emit('data-a',this.a); B接收数据: mounted(){ Event_z.$on('data-a',a =>{ this.c=a; })
必须是箭头函数html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> <l-a></l-a> <l-b></l-b> <l-c></l-c> </div> <template id="la"> <div> <h1>la: {{a}}</h1> <button @click="atoc">点击发送</button> </div> </template> <template id="lb"> <h2>lb: {{b}}</h2> </template> <template id="lc"> <h3>lc:{{c}}</h3> </template> </body> <script> var Event_z = new Vue(); new Vue({ el: '#app', data:{ }, components:{ 'l-a':{ template:'#la', data:function () { return { a:"zheshi A" } }, methods:{ 'atoc':function () { Event_z.$emit('data-a',this.a); console.log("发送成功") } } }, 'l-b':{ template: '#lb', data:function () { return { b:"zheshi B" } } }, 'l-c':{ template: '#lc', data:function () { return { c:"4" } }, mounted(){ Event_z.$on('data-a',a =>{ this.c=a; console.log('接收成功') }) } } } }) </script> </html>