I'm thinking about creating an event bus class that includes methods like on, off, emit, and once, while ensuring they're all typed.
Using TypeScript generics means I can define my events neatly with a structure like EventMap = Record<string, any>.
I'll also introduce an injection key, const EventBusKey: InjectionKey<EventBus<EventMap>> = Symbol('EventBus'), to enable smooth integration.
For the plugin, I want to create createEventBusPlugin<EventMap>(), which returns an object with an install function while managing the bus type across the app.Defining a typed event bus
I'm thinking about defining global events, like 'user:login' with an ID and a 'toast' event with an optional message and type for success or error.
Next, I'm creating a TypedEventBus class that will hold listeners for these events using generics. It includes methods like on, off, and emit that will manage these events effectively.
For the plugin, I’ll set up createEventBusPlugin<Events>() to create a bus, an injection key, and a plugin installation that provides the bus to the app, making it available for use.Crafting the event bus plugin
I'm realizing that the plugin’s generic parameter needs to be satisfied at compile time instead of at runtime. So, I can use const { plugin, key, bus } = createEventBusPlugin<GlobalEvents>(); in my main file and then call app.use(plugin);.
When I inject the bus in a component, it seems like key and bus types might get lost, so I need to export them.
To keep it simple, I could just create a non-generic plugin for specific GlobalEvents, allowing for easy customization in the plugin file. Now, I'll prepare the API and demonstrate how to use it in components.Defining TypeScript for events
I need to provide TypeScript definitions for this.$events through module augmentation of ComponentCustomProperties. This way, TypeScript will recognize it.
This adds robust typing for $events when using the Options API. For the Composition API, I can use inject(EventBusKey) to maintain type safety.
I’m also considering whether to allow wildcard events with on('*', ...), but that could compromise type safety, so I’ll stick with strictly typed events. I want to ensure the plugin is well-documented and properly implemented for both Node and the browser.Implementing the event bus plugin
I'm working on the event-bus.ts file where I create an EventBus class. It has methods for handling events, like on, once, off, and emit. The payload types are defined through a generic Events interface, allowing flexibility.
I need to manage slight mismatches in type safety, especially since 'user:logout' has a void payload. To keep it clean, I’ll modify the emit method to handle events with and without payloads. Instead of using void, I could use null or an empty object for enhancements.
For simplicity, I want to ensure the plugin compiles correctly. I’ll include the necessary TypeScript definitions for seamless integration with Vue, ensuring that handlers work correctly while providing clear documentation.Structuring the response
I'm thinking about organizing the answer into clear sections. First, I’ll provide the full implementation of the event bus plugin for Vue 3 with TypeScript in a file called event-bus.ts.
Next, I’ll include examples of how to use this plugin within main.ts and in components.
Additionally, I can add a note about defining custom GlobalEvents, since that’s important for users wanting flexibility. I want to avoid generic phrases like "Great question" and dive straight into the code to keep things efficient and focused. Alright, let’s get started! Below is a ready-to-use Vue 3 plugin that provides a typed global event bus with TypeScript support for both Composition API and Options API.
You can copy this into something like src/plugins/eventBus.ts.
1. Plugin implementation (eventBus.ts)
ts
2. Registering the plugin (main.ts)
ts
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { EventBusPlugin } from './plugins/eventBus';
const app = createApp(App);
app.use(EventBusPlugin);
app.mount('#app');
3. Usage examples
3.1. Composition API
ts
// SomeComponent.vue
<script setup lang="ts">
import { useEventBus } from '@/plugins/eventBus';
const bus = useEventBus();
// Emit events
function login() {
bus.emit('user:login', { userId: '123' });
}
function logout() {
bus.emit('user:logout'); // payload is void, so no argument needed
}
function showToast() {
bus.emit('toast:show', { message: 'Saved!', type: 'success' });
}
// Listen to events
const unsubscribe = bus.on('toast:show', (payload) => {
console.log('Toast:', payload.message, payload.type);
});
// Example: listen once
bus.once('user:login', (payload) => {
console.log('User logged in once:', payload.userId);
});
</script>