Communicating between 2 components

I’m fairly new to Vue, so hopefully I’m asking this the correct way.

I want to emit an event and have a different component (NOT the parent) listen for that emit and do something. I know this was possible with Vue 2 with $on, but not possible in Vue 3.

I’ve tried reading Vue 3 docs, but they only talk about parent->child and child->parent not child->child. I also looked in mitt https://github.com/developit/mitt, but that doesn’t seem to work in Ionic Vue.

Has anybody run into this with Ionic Vue and know a solution?

Hmm, so the best idea I could think of in this situation would be to

  • emit event from child cmp-A
  • parent component listens for that event
  • parent component calls method on child cmp-b

Or something like Vuex which would be able t to publish updates to some state and have all the components react to that.

The composition api comes to the rescue… I used tiny-emitter but I suspect it would work with the other library also

// eventbus.ts
import { TinyEmitter } from "tiny-emitter";
const emitter = new TinyEmitter();
const eventBus = () => {
  return { emitter };
};
export default eventBus;

Listen For Event

/* import the eventbus... */
import eventBus from "./views/eventbus";

export default defineComponent({
  name: "App",
  components: { },
  setup() {
    onMounted(() => {
      eventBus().emitter.on("test-event", (payload: any) => {
        debugger;
        console.log("test-event", payload);
      });
    });
  },
});

Fire off an event

/* import the eventbus... */
import eventBus from "./eventbus";

export default {
  name: "Page1",
  components: { },
  setup() {
    return {
      sendEvent: () => {
        eventBus().emitter.emit("test-event", { time: new Date() });
      },
    };
  },
};
2 Likes

thats cool, , sort of weird to skip around the infrastructure… now I am trying to overcome event problems too… I can fire my (on ) handler, but I need to manipulate a ui component (change its background), but I cannot for the life of me determine how I get thru refs or ‘this’

I provided my own similar package to try to get into context, but haven’t been successful…

in the above

console.log("test-event", payload);

can u replace that with some content access ? like

  this.$refs.style="backgroundColor:grey;";

i get

cannot access $refs of undefined

Not sure what you mean by skip around the infrastructure? The official vue documentation recommends using a third party library.

As for the you second question, it is a completely different topics, so I suggest you mark this as solved and create a new entry.

this was not my topic,
I have one already

this is events forwarded up the chain from grandchild

the event arrived, but needed to look of the element of the ref to use on the element method call.

this.$refs.slides1.$el.slidePrev()

works perfectly. thanks!