Gorilka
Gorilka

Reputation: 504

Event bus for only one view

I need to create an event bus that only works on one page, this is important because I have several pages(views) with the same event listener names. Also some components are also consist of components and I cannot just use global event bus. Which approach would you take?

Upvotes: 2

Views: 448

Answers (1)

blaz
blaz

Reputation: 4068

For a solution using event bus, I would give the component a prop as identity, let's name it customId. You can use library such as nanoid for default value, and set custom one for your target page

export default {
  name: 'MyComponent',
  props: {
    customId: {
       type: String,
    }
  },
  data() {
    return {
      innerId: this.customId || nanoid(),
    }
  }
}

in your target page

<my-component custom-id="event-listener" />

In your event bus, add component's customId as a part of your message, so in each instance of MyComponent, only the targeted one would pick up the data

YourEventBus.$emit('custom-event', {
  target: 'event-listener',
  payload: yourData
});

Upvotes: 1

Related Questions