本文只在我的博客和 SegmentFault 社區我的專欄發表,轉載請註明出處
我的博客: https://zengxiaotao.github.io
SegmentFault 我的專欄: https://segmentfault.com/blog...html
組件是 vue 的核心部分,而組件之間通訊方式是必不可少的。 父子之間的通訊方式很簡單,父組件經過 props 向子組件傳值,而子組件經過自定義事件把數據傳遞迴父組件,那麼非父子關係組件怎麼進行通訊?
Vue2.x 廢棄了 broadcast 和 dispatch 以後,能夠經過 vuex ,還有 event bus 來解決。這裏不講 vuex ,講起來是另一個話題,就講一下怎麼在非父子組件之間經過 event bus 進行通訊。vue
首先咱們要實現的效果是git
上下分別是 foo組件和 bar 組件,它們之間是非父子關係,分別點擊各自的 button ,另外一個組件的 count 對應增長。github
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>非父子組件通訊</title> <script src="https://unpkg.com/vue@2.1.8/dist/vue.js"></script> </head> <body> <div id='app'> <foo></foo> <hr> <bar></bar> </div> </body> </html>
以上就是這個 demo 結構。看看 js 的實現vuex
// 註冊一個空的 Vue 實例,做爲 ‘中轉站’ var eventBus = new Vue({}) // foo 組件 var foo = { template: '<div><p>the count of foo is {{fooCount}}</p>' + '<button @click="addBar">add bar\'s count</button></div>', data: function() { return { fooCount: 0 } }, methods: { addBar: function() { // 觸發事件 eventBus.$emit('addBar') } }, mounted: function() { eventBus.$on('addFoo', function(num) { this.fooCount +=num }.bind(this)) // 這裏必須將 this 綁定在組件實例上。若是不使用 bind , 也可使用箭頭函數。 } } // bar 組件 var bar = { template: '<div><p>the count of bar is {{barCount}}</p>' + '<button @click="addFoo">add foo\'s count</button></div>', data: function() { return { barCount: 0 } }, methods: { addFoo: function() { // 觸發事件,同時傳遞一個參數 eventBus.$emit('addFoo', 2) } }, // 在 組件建立的鉤子函數中 監聽事件 mounted: function() { eventBus.$on('addBar', function() { this.barCount++ }.bind(this)) } } var vm = new Vue({ el: '#app', components: { foo, bar } })
以上就實現了一個簡易的 非父子組件之間的通訊方式。經過 event bus ,在一個組件建立時的鉤子函數中監聽 某個事件,而在須要與其進行通訊的組件中觸發這個函數,同時交換數據。 segmentfault
固然,event bus 只適於某些不復雜的場景,在須要頻繁進行組件通訊的狀況下,仍是應該儘可能使用 Vuex ,不只使用上更加簡單,同時數據流的流向也會相對清晰。app
全文完函數