Home > Software engineering >  component supposed to listen to emitted events from child
component supposed to listen to emitted events from child

Time:10-26

I've starting exercising vuejs and I've learned that to communicate data from child component back to parent component we use this.$root.$emit('name-of-event', myobject);

which would be received from parent with the help of this.$root.$on('name-of-event');

In the other hand, I got a vuejs project which I use to compare what I had learned with what is implemented in it and there I found that the component listening to my event is not the parent of that component (the tag of the component triggering the event is not rendered in the one who is listening to it)

My question: is it always the case that the direct parent is the one who listens to the triggered event ? could other component be listening to emitted events ?

myAcomponent.vue :

    updateDate(value) {

 //body of updateDate method
            this.$root.$emit('date-updated', this.project);
          
    }

myBcomponent.vue :

<script>
      created() {
        this.$root.$on('date-updated', project => {
          this.updateproject(project);
        });
     }
</script>

<template>
//no call in template for myAcomponent
</template>

CodePudding user response:

Is it always the case that the direct parent is the one who listens to the triggered event ? - Answer is Yes, Now 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.

CodePudding user response:

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.

  • Related