Tuesday, 12 July 2022

Event Bus implementation in Vue

 In any application data sharing among various components/services are key to maintain data flow. In vue, different data sharing methods are:

  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>

No comments:

Post a Comment