Data Pass Between Components using EventBus in Vue 3

We can share information between any components using EventBus. In Vue 2, using $emit we can do this task. But In Vue 3, $on, $off and $once methods are removed from the instance completely. So, we need to use an external library to handle it for us.

Table of Contents

  1. Install Package & Config
  2. Emit & Listen Event
  3. Test in One Component

Install Package & Config

We’ll use mitt to do event bus task. Install this pack:

npm install --save mitt

Now, open main.js and config like this:

main.js
import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'

const eventBus = mitt()
const app = createApp(App)

app.config.globalProperties.eventBus = eventBus
app.mount('#app')

Emit & Listen Event

Let’s try to pass data from ComponentA to ComponentB. In ComponentA, emit event like:

ComponentA.vue
<template>
  <div>
    <button v-on:click="emitEvent" >Emit Event</button>
  </div>
</template>

<script>
export default {
  name: 'ComponentA',
  methods: {
    emitEvent() {
      this.eventBus.emit('test', 'Welcome to MNP!')
    },
  },
}
</script>

To receive data in ComponentB, set a listener:

ComponentB.vue
<template>
  <div>
    Component B
  </div>
</template>

<script>
export default {
  name: 'ComponentB',
  mounted () {
    this.eventBus.on('test', (args) => {
      alert(args)
    })
  },
}
</script>

So, we’ve passed data between two components.

Test in One Component

Let’s test the above thing in one component:

App.vue
<template>
  <div>
    <button v-on:click="emitEvent" >Emit Event</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  mounted () {
    this.eventBus.on('test', (args) => {
      alert(args)
    })
  },
  methods: {
    emitEvent() {
      this.eventBus.emit('test', 'Welcome to MNP!')
    },
  },

}
</script>

So, using event bus we can pass data between any components.

That’s all, folks. Thanks for reading.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.