Event Bus implementation in Vue

  1. Props: Allow to pass data from parent to child component.
  2. Emit: Allow to pass data from child to parent component.
  3. Vuex Store: Allow to share data across components.
import mitt from 'mitt';
export default mitt();
<template>
<div class="hello">
<input v-model="message" />
<button
@click="onPublish">publish</button>
</div>
</template>
<script>
import eventbus from "@/eventbus";
export default {
name: "HelloMessagePublish",
data() {
return {
message: "",
};
},
methods: {
onPublish() {
eventbus.emit("getMessage", this.$data.message);
},
},
};
</script>
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
import eventbus from "@/eventbus";
export default {
name: "HelloMessageDisplay",
data() {
return {
msg: "",
};
},
mounted() {
eventbus.on("getMessage", (e) => {
this.$data.msg = e;
});

},
};
</script>
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
import eventbus from "@/eventbus";
export default {
name: "HelloMessageDisplay2",
data() {
return {
msg: "",
};
},
mounted() {
eventbus.on("getMessage", (e) => {
this.$data.msg = e;
});

},
};
</script>
<template>
<div id="app">
<HelloMessagePublish />
<HelloMessageDisplay />
<HelloMessageDisplay2 />

</div>
</template>
<script>
import HelloMessageDisplay from "./components/HelloMessageDisplay";
import HelloMessageDisplay2 from "./components/HelloMessageDisplay2";
import HelloMessagePublish from "./components/HelloMessagePublish";
export default {
name: "App",
components: {
HelloMessageDisplay,
HelloMessageDisplay2,
HelloMessagePublish,

},
};
</script>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Binod Mahto

Binod Mahto

141 Followers

Solution Architect & Full Stack Developer. Passionate about Software designing & development and Learning Technologies and Love to share what I learn.