๐Ÿš€๐Ÿš€ Integrating the PubSub Pattern in Vue 3 ๐Ÿš€๐Ÿš€

ashok_24_99c5ee15c6ad5150

Ashok

Posted on August 15, 2024

๐Ÿš€๐Ÿš€ Integrating the PubSub Pattern in Vue 3 ๐Ÿš€๐Ÿš€

As Vue.js applications grow, managing communication between components can become complex. A powerful solution to decouple components and manage event-driven communication is the Publish-Subscribe (PubSub) pattern. By integrating this pattern into Vue.js, you can create a flexible and maintainable way to handle events across your application.

What is the PubSub Pattern?

The PubSub pattern allows components to publish events that other components can subscribe to. This decouples components, making your application more modular and easier to manage. Using PubSub, you can trigger actions or update states in one component based on events in another without needing direct parent-child communication.

Implementing the PubSub Pattern in Vue.js

Letโ€™s walk through how to implement the PubSub pattern in a Vue.js application using a simple, reusable event bus.

Step 1: Create a PubSub Event Bus
In Vue.js, you can create a simple event bus using Vueโ€™s provide and inject APIs or by creating a standalone PubSub object.

// pubsub.js
export const PubSub = {
    subscribers: new Map(),

    subscribe(event, subscriber) {
        if (!this.subscribers.has(event)) {
            this.subscribers.set(event, []);
        }
        this.subscribers.get(event).push(subscriber);
    },

    unsubscribe(event, subscriber) {
        if (this.subscribers.has(event)) {
            const updatedSubscribers = this.subscribers.get(event).filter(sub => sub !== subscriber);
            if (updatedSubscribers.length > 0) {
                this.subscribers.set(event, updatedSubscribers);
            } else {
                this.subscribers.delete(event);
            }
        }
    },

    publish(event, payload) {
        if (this.subscribers.has(event)) {
            this.subscribers.get(event).forEach(subscriber => {
                subscriber(payload);
            });
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

Step 2: Using PubSub in Vue Components

Now that you have your PubSub event bus, you can use it in your Vue components to subscribe to events, publish events, and unsubscribe when the component is destroyed.

Component-1

<template>
  <div>SubscriberComponent-1 {{ count }}</div>
</template>

<script  setup>
import { onMounted, ref } from "vue";
import { PubSub } from "./pubsub.js";

const count = ref(0);

const event = (payload) => {
  console.log("Received payload:", payload);
  count.value = payload;
};

onMounted(() => {
  PubSub.subscribe("myEvent", event);
});
</script>


Enter fullscreen mode Exit fullscreen mode

Component-2

<template>
  <div>SubscriberComponent-2 {{ count }}</div>
</template>

<script  setup>
import { onMounted, ref } from "vue";
import { PubSub } from "./pubsub.js";

const count = ref(0);

const event = (payload) => {
  console.log("Received payload:", payload);
  count.value = payload;
};

onMounted(() => {
  PubSub.subscribe("myEvent", event);
});
</script>

Enter fullscreen mode Exit fullscreen mode

Publishing an Event:

<template>
  <div>PublisherComponent <button @click="publishEvent">post</button></div>
</template>

<script  setup>
import { PubSub } from "./pubsub.js";

let count = 1;

const publishEvent = () => {
  ++count;
  PubSub.publish("myEvent", { message: `Hello, PubSub! ${count}` });
};
</script>


Enter fullscreen mode Exit fullscreen mode

Image description

Why Use the PubSub Pattern in Vue.js?

  • Decoupling: The PubSub pattern helps to decouple components, making your application more modular and easier to maintain.
  • Event-Driven Architecture: It enables an event-driven approach, where components can react to events without being directly connected.
  • Flexibility: The PubSub pattern allows you to manage events across different parts of your application without the need for complex prop drilling or state management.

Conclusion

By integrating the PubSub pattern into Vue.js, you can manage communication between components more effectively, leading to a cleaner, more modular application architecture. This pattern is particularly useful for large applications where components need to communicate frequently without becoming tightly coupled.

Feel free to use this approach in your own Vue.js projects, and adapt it to suit your needs. Happy coding!

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
ashok_24_99c5ee15c6ad5150
Ashok

Posted on August 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

ยฉ TheLazy.dev

About