I recently implemented a basic Event bus in my application to dynamically change styles on a page, and it's functioning correctly. The event bus is triggered using the $emit
and $on
methods as shown below:
EventBus.$on
and
EventBus.$emit('call-modal', { type: 'success' });
Now I'm wondering how I can modify it so that instead of utilizing $on
and $emit
, I can use this.$root.$emit
to make it accessible across all components. I attempted to implement this change, but it's not working currently. Could someone explain why?
Below is the snippet from my App.vue file:
<template >
<div id="app">
<bankAccount>
</bankAccount>
<div :class="['modal', `modal--type--${modalType}`]" v-show="showModal">
<slot name="title">e</slot>
<slot name="description"></slot>
</div>
</div>
</template>
<script>
import bankAccount from './components/bankAccount.vue'
import Vue from 'vue'
export const EventBus = new Vue()
export default {
name: 'app',
components: {
bankAccount,
},
data() {
return {
showModal: false,
modalType: 'default',
}
},
created() {
EventBus.$on('call-modal', obj => {
this.showModal = true
this.modalType = obj.type
})
},
}
</script>
<style>
.modal {
height: 100px;
width: 300px;
border: solid gray 2px;
}
.modal--type--success {
border-color: green;
}
.modal--type--danger {
border-color: red;
width: 100%;
}
.modal--type--warning {
border-color: yellow;
width: 100%;
}
</style>
And here is an excerpt from my component:
<template>
<div>
<button class="pleeease-click-me" @click="callModal()">Click me</button>
</div>
</template>
<script>
import { EventBus } from '../App.vue';
export default {
name: 'bankAccount',
data() {
return {
showModal: false
}
},
methods: {
callModal() {
this.showModal = !this.showModal
EventBus.$emit('call-modal', { type: 'success' });
}
}
}
</script>
<style scoped>
.modal {
height: 100px;
width: 300px;
}
</style>