非父子組件之間的通訊,能夠經過一個空的 Vue 實例做爲中央事件總線(事件中心),用他來觸發事件和監聽事件。javascript
在這裏,若是是工做中的新手看了官網的例子直接上手寫,會有些發懵。這個做爲事件總線空的 Vue 實例我該寫哪裏去?由於工做中咱們的組件都是互相獨立的,不可能寫一塊兒的,做用域是不一樣的,因此須要稍做調整html
new Vue({ el: '#app', data:{ Event: new Vue() }, render: h => h(App) })
vm.$root.Event 來訪問咱們定義的事件發射器 Event
好比我在 Hello.vue 組件中想發送數據到 Vue.vue 組件中vue
<template> <div class="hello"> <h3>我是 {{name}} 組件</h3> <button @click="send">發送數據到Vue組件中</button> </div> </template> <script> export default { data(){ return { name: 'Hello' } }, methods:{ send(){ // 觸發組件 Hello 中的事件 // $emit(事件名,數據) this.$root.Event.$emit('hello',this.name) } } } </script>
在 Vue.vue 組件中進行接收java
<template> <div class="Vue"> <h3>我是 {{name}} 組件</h3> </div> </template> <script> export default { data(){ return { name: '' } }, mounted(){ // 在組件 Vue 建立的鉤子中監聽事件 // $on(事件名,數據) this.$root.Event.$on('hello',name => { this.name = name }) } } </script>
這樣就能夠實現數據的通訊了api