DEV Community

mixbo
mixbo

Posted on

EventBus on Vue.js

Alt Text

In Vue.js component communication maybe use props, vuex
or events.

props can pass data to child then child can pass to child again, if you have multiple children components use props to the end children. that is crazy things, why? you must pass data from first child to the last child and all child will props it. data will through all the component.

vuex can solve props problem, you can defined data to store. after all included the store object, like child or component will operation data and share data. that make you no need pass data from first child to the end of child. but vuex must included first in every you need child or component.

You know props, vuex all have use scene. in my team we use
eventbus pass data to whatever you want child or component.

// event-bus.js
import Vue from 'vue'
export default new Vue

// Parent.vue
<script>
import eventBus from './event-bus'
export default {
  method:{
    onClick(){
      eventBus.$emit('click',{name:'foo'})  
    }
  }
}
</script>

// ChildA.vue
<script>
import eventBus from './event-bus'
export default {
  mounted(){
    eventBus.$on('click',(data)=>{
      console.log(data) // {name:'foo'}
    })  
  }
}
</script>

// ChildB.vue
<script>
import eventBus from './event-bus'
export default {
  mounted(){
    eventBus.$on('click',(data)=>{
      console.log(data) // {name:'foo'}
    })  
  }
}
</script>

Enter fullscreen mode Exit fullscreen mode

If you trigger click event at Parent then ChildA ChildB will trigger call back.

eventbus can isolate logic just need subscribe and dispatch event you need data will got. i think eventbus more suit pass data from component to other component witch component no more relation.

Hope it can help you :)

Top comments (0)