Vue非父子组件之间的通信
上一篇文章讲了Vue父子组件之间的通信,这里就介绍一下非父子组件之间是如何通信的。
非父子组件的通信一般有两种方法,一种是通过eventHub,也就是创建一个空的vue对象作为组件间通信的介质;另一种则是通过vuex状态管理。这里介绍的是第一种方法。
先贴上代码:
1 <div id="app"> 2 <foo></foo> 3 <bar></bar> 4 </div> 5 6 <template id="foo"> 7 <div> 8 <p>the count of d is {{fooCount}}</p> 9 <button @click="addBar" >foo</button> 10 </div> 11 </template> 12 13 <template id="bar"> 14 <div> 15 <p>the count of d is {{barCount}}</p> 16 </div> 17 </template> 18 19 <script> 20 21 // foo组件 22 var foo={ 23 template: '#foo', 24 data(){ 25 return{ 26 fooCount:0 27 } 28 }, 29 methods:{ 30 addBar(){ 31 this.fooCount++; 32 eventHub.$emit('addBar',this.fooCount); 33 } 34 } 35 }; 36 37 // bar组件 38 var bar={ 39 template: '#bar', 40 data(){ 41 return{ 42 barCount:0 43 } 44 }, 45 created(){ 46 eventHub.$on('addBar',(arg)=>{ 47 this.barCount=arg; 48 }) 49 } 50 } 51 52 // eventHub 53 var eventHub = new Vue(); 54 55 new Vue({ 56 el:"#app", 57 components:{ 58 'foo':foo, 59 'bar':bar 60 } 61 }); 62 63 </script>
整个原理是比较简单的,总结一下要点:
1.foo组件是通过$emit(name,val)方法将信息发送出去,name表示发送信息的名字,val表示发送的内容
2.然后bar组件里通过$on(name,callback)里获取到foo组件发送的内容,name表示foo组件发送的信息名字,callback表示一个回调函数,来执行获取信息后的一些操作

浙公网安备 33010602011771号