After watching a tutorial on using an event bus to communicate between sibling components in Vue, I came across an interesting approach. The tutorial demonstrated passing data from a parent component to child components as props, then modifying that prop in one child and using an event bus to pass it onto the other child.
This method got me thinking - why rely on props when each sibling component can have its own data? So, I decided to implement my solution:
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
export const bus = new Vue() // Event Bus
new Vue({
render: h => h(App),
}).$mount('#app')
App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<ComponentA></ComponentA>
<ComponentB></ComponentB>
</div>
</template>
<script>
import ComponentA from './components/ComponentA.vue'
import ComponentB from './components/ComponentB.vue'
export default {
name: 'App',
components:{
ComponentA,
ComponentB
}
}
</script>
ComponentA.vue
<template>
<div>
<h1 @click="changeTitle">Component A</h1>
</div>
</template>
<script>
import { bus } from '../main'
export default {
name: 'ComponentA',
data(){
return{
title: ''
}
},
methods:{
changeTitle(){
this.title = 'Title emitted from A to B'
bus.$emit('titleChanged',this.title)
}
}
}
</script>
ComponentB.vue
<template>
<div>
<h1>Component B -> {{title}}</h1>
</div>
</template>
<script>
import { bus } from '../main'
export default {
name: 'ComponentB',
data(){
return{
title: ''
}
},
created(){
bus.$on('titleChanged', (payload) =>{
this.title = payload
})
}
}
</script>
Does my implementation raise any red flags? Am I missing out on some benefits of using parent data instead of individual component data?