假设子组件A向子组件B传递信息
现在Vue实例中的data中设置名为bus 的Vue实例中介.子组件A在设置监听事件,并设置方法,子组件A的方法为(假设点击事件),通过$root.bus.emit()提交当前的信息给子组件B的自定义事件子组件B通过声明周期钩子,通过created,在实例刚创建的时候,监听这个函数,通过$root.bus.$on('自定义事件',function(value){})接收一个子组件A的参数value总而言之
子组件A用$root.bus.emit('自定义事件',value)传出数据子组件B用$root.bus.$on('自定义事件',function(value){})接收数据 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div id="app"> <a-component></a-component> <b-component></b-component> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> Vue.component('a-component',{ template:`<button @click='handle'>点击传递值</button>`, data(){ return{ aaa:'我是来自a的内容' } }, methods:{ handle(){ this.$root.bus.$emit('lalala',this.aaa) } } }) Vue.component('b-component',{ template:`<div>{{count}}</div>`, created:function(){ this.$root.bus.$on('lalala',function(value){ alert(value) console.log(this) }) } , data(){ return{ count:0 } } }) const app = new Vue({ el:"#app", data:{ bus: new Vue() } }) </script> </body> </html>点击子组件B按钮获得子组件A中的值
