組件是Vue核心的一塊內容,組件之間的通信也是很基本的開發需求。組件通信又包括父組件向子組件傳數據,子組件向父組件傳數據,非父子組件間的通信。前兩種通信Vue的文檔都說的很清楚,但是第三種文檔上確只有下面的幾句
具體如何去實現卻沒有很詳細的說明,於是自己試着進行了實現。先看下簡單的通信效果:
就是點擊了一個組件,另一個組件的數字遞加。
html如下:
<div id="app"> <component-a></component-a> <component-b></component-b> </div>
再來看一下如何實現每一個組件:
var bus = new Vue() //首先建立一個空的Vue實例作為事件的中轉 Vue.component('component-a',{ template: `<div><button @click="incrementB">{{masgA}}</button></div>`, //添加點擊事件incrementB ,因為點擊A需要增加B data () { return { masgA : 0 } }, methods: { incrementB: function () { //增加B的事件 bus.$emit('incrementB') //中轉站bus 觸發incrementB事件 } }, mounted: function () { var _this = this bus.$on('incrementA',function(){ //中轉站bus自定義increamentA事件用來增加msgA,這個事件最終由組件B進行觸發 _this.masgA ++ })
//bus.$on('incrementA',()=>{ //這里也可以用箭頭函數,就不會有_this這個變量了,因為箭頭函數不會改變this指向
// this.masgA ++
//}) } })
從上面的代碼可以看出真正的改變方法是通過bus里注冊監聽事件來實現的,同理代component-b也是一樣
Vue.component('component-b',{ template: `<div><button @click="incrementA">{{masgB}}</button></div>`, data () { return { masgB : 0 } }, methods: { incrementA: function () { bus.$emit('incrementA') } }, mounted: function(){ bus.$on('incrementB',() => { this.masgB ++ }) } })
完整代碼如下,可直接復制運行

1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>非父子組件通信</title> 6 </head> 7 <body> 8 <div id="app"> 9 <component-a></component-a> 10 <component-b></component-b> 11 </div> 12 <script src="https://unpkg.com/vue/dist/vue.js"></script> 13 </body> 14 <script> 15 var bus = new Vue() //首先建立一個空的Vue實例作為事件的中轉 16 17 Vue.component('component-a',{ 18 template: `<div><button @click="incrementB">{{masgA}}</button></div>`, //添加點擊事件 19 data () { 20 return { 21 masgA : 0 22 } 23 }, 24 methods: { 25 incrementB: function () { 26 bus.$emit('incrementB') 27 } 28 }, 29 mounted: function () { 30 var _this = this 31 bus.$on('incrementA',function(){ 32 _this.masgA ++ 33 }) 34 bus.$on('incrementA',()=>{ 35 this.masgA ++ 36 }) 37 } 38 }) 39 40 Vue.component('component-b',{ 41 template: `<div><button @click="incrementA">{{masgB}}</button></div>`, 42 data () { 43 return { 44 masgB : 0 45 } 46 }, 47 methods: { 48 incrementA: function () { 49 bus.$emit('incrementA') 50 } 51 }, 52 mounted: function(){ 53 bus.$on('incrementB',() => { 54 this.masgB ++ 55 }) 56 } 57 }) 58 59 var vm = new Vue({ 60 el: "#app" 61 }) 62 </script>
同時也可以看出這么做僅有兩個組件就有些麻煩,事件的流向不是很清晰,所以在出現復雜的場景時需要使用VueX進行管理。
本文結束,有任何不同的意見歡迎在留言區討論。
注:本文出自博客園http://www.cnblogs.com/mdengcc/ 轉載請注明出處