Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // use-event-bus.ts
- import { provide, inject } from '@vue/composition-api';
- import EventEmitter from 'eventemitter3';
- const EventBusDefaultSymbol = Symbol('Default event bus symbol');
- export function provideEventBus(eventBus: EventEmitter, eventBusSymbol = EventBusDefaultSymbol) {
- provide(eventBusSymbol, eventBus);
- return () => provide(eventBusSymbol, undefined);
- }
- export function useEventBus(eventBusSymbol = EventBusDefaultSymbol) {
- const eventBus = inject(eventBusSymbol);
- if (!eventBus) {
- throw new Error('Event bus not found');
- }
- return eventBus;
- }
- // parent.vue
- import { provideEventBus } from '../../composition/use-event-bus';
- ...
- setup(props, context) {
- const eventBus = new EventEmitter();
- const eventBusSymbol = Symbol('rsm network event bus symbol');
- provideEventBus(eventBus, eventBusSymbol);
- return {
- eventBus,
- eventBusSymbol,
- };
- },
- // child.vue
- import { useEventBus } from '../../composition/use-event-bus';
- ...
- setup(props, context) {
- const eventBusSymbol = props.eventBusSymbol as symbol;
- const eventBus = eventBusSymbol ? useEventBus(eventBusSymbol) : null;
- return {
- eventBus,
- };
- },
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement