Home > Software design >  How to access a method on a parent from a grandchild
How to access a method on a parent from a grandchild

Time:10-08

I am not sure what else to call this. I have a file, lets call it parent.vue. it has the following

PARENT.vue

<template>
  <input-box
    :room="currentRoom"
    v-on:messagesent="getMessages"
    class="dark:bg-gray-800 px-6 pb-6 pt-4 dark:border-t-2 dark:border-gray-600 bottom-0 sticky" />
</template>
method:
  getMessages() {
    axios.get('/chat/room/'   this.currentRoom.id   '/messages')
    .then(response => {
      this.messages = response.data;
    })
    .catch(error => {
      console.log(error);
    })
  },

Then I have a child which calls the v-on anytime something happens. The issue is, I need to call that from a child inside the child. "aka the grandchild" Inside the CHILD I have inside a method

this.$emit('messagesent');

How can I accomplish the same thing inside the grandchild.

CodePudding user response:

Well that was a blank moment on my part.

Using

this.$parent.$emit()

Gave me the ability to send it up the chain. This is exactly what I wanted.

CodePudding user response:

Not if you want to maintain encapsulation. Grandparent is not supposed to know about grandchild. It knows about parent, but not that there are sub-components or how many. In principle, you can swap one implementation of grandparent out for another that doesn't have multiple layers. Or has even more layers to get to child. And you could put child into a top-level component.

You already know about the notion of a global event bus. A bus doesn't have to be global, though. You can pass it down the props chain. (You could use grandparent itself as the bus, but that would expose it to its children; better hygiene to make a real bus.)

This distinguishes top-level components from sub-components: a sub-component will receive a bus prop to perform the functions of the top-level component that it helps to implement. A top-level component will originate the bus.

For more details check out the below link

https://andrejsabrickis.medium.com/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860

  • Related