0

I would like to emit an event from App.vue which is a main component to another component. EventBus.$emit from App.vue, EventBus.$on on child/another component is not working. Since there is no child relation directly between these, I cannot use @custom-event="" either

How can I throw an event from App.vue to another component?

That's what I do. It is working all of the other components. Here my components' folder structure

-src
-pages
  -main-page
    -MainPage.vue  $on
-event
-constant
-store
-router
App.vue  --> $emit
main.js
Can Cinar
  • 401
  • 1
  • 8
  • 18
  • How is it not working for you, can you elaborate a bit more? Also, your sentence `Since there is no child relation directly between these` doesn't make sense since EventBus works independently, you just need to make sure it imports from the right source. – Yom T. May 23 '19 at 06:11
  • Look at the event bus method of passing events described in https://stackoverflow.com/a/54940012/1030527 You can use it to send events to parents or child components – bernie May 23 '19 at 06:17
  • EventBus is not working as well as I mentioned, imports checked. If I use EventBus in other components except App.vue, it is working. However, in App.vue which is the top of element or page whatever you call in my project. – Can Cinar May 23 '19 at 06:21

1 Answers1

1

You say the EventBus method isn't working but it should be so I'll assume you're doing it wrong. Do something like this:

Create eventBus.js

import Vue from 'vue';
export const EventBus = new Vue();

In any of your single file components, import it:

import { EventBus } from '/src/path/to/eventBus.js';

Trigger an event in a component:

EventBus.$emit('some-event-raised', { someData: "bob" })

In any other component, do the import again and then listen:

EventBus.$on('some-event-raised', obj => {
  console.log(`some-event-raised triggered [${obj.someData}]`)
});
webnoob
  • 15,747
  • 13
  • 83
  • 165
  • That's what I do. It is working all of the other components. I edited my question to be more clear – Can Cinar May 23 '19 at 08:38
  • How about is you emit / listen using `this.$root.emit()` / `this.$root.on()`? I can't remember if this is part of the default Vue stuff or just in the Quasar framework I use (you should check it out BTW, handles a lot of things like this for you) – webnoob May 23 '19 at 10:00