[Vuejs]-Component supposed to listen to emitted events from child

0👍

Is it always the case that the direct parent is the one who listens to the triggered event ? – Answer is Partially Yes, There are two scenarios or use cases :

  1. If you are working on a large application and there is a need to share data between multiple components and these components don’t have any relation with each other, then you have to use a state management solution. You can use Pinia – which is the state management library recommended by the Vue core team.
  2. If you want to share the data only between the siblings under single parent, In that case you can give a try to this solution.
    • Pass data from one child to parent component using event emitter.
    • Capture the event in parent and then pass back to another child by using props.

0👍

there is a better way to improve the event emit

lets say you have component A and B you want to transfer data from A to B also they don’t have direct relationship

1.create JavaScript file and add the below code on JavaScript file save it FIleName.js

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

2 on component A.vue emit the event on methods or on api call

import {EventBus} from "path/FIleName.js";



 update(data){

    EventBus.$emit("event-name",Data);
     }

3 the last thing you want to do is listen on a component B.vue which you want to get the data or the event and fire a function to do something with the data you passed

import {EventBus} from "@/service/EventBus.js";
 created() {
    EventBus.$on("gallery-created",(Data) =>{
      this.MyFunction(Data);
    })
  },

By doing this you can pass an event and data to any component using event bus method.

Leave a comment