vuejs3emit

vue3 emit from sub child to top level


I have installed vue-cookie-accept-decline a package to show the privacy cookie banner in my App.vue. And now I would like to call some methods from different components of my app.

App.vue

<template>
  <router-view/>
  <vue-cookie-accept-decline @reset='reset'....> 
</template>

I can refer to my vue-cookie-accept-decline template by ref='myPanel1' so I did the following script and I would like to call it by an emit reset to restore the banner.

setup() {
  const myPanel1 = ref({});

   reset(() => {
      myPanel1.value.removeCookie()
      myPanel1.value.init()
   });

  return {
  myPanel1,
  reset
  }
}

This approach is not good for me because I don't know the level of the component calling the emit method. How can I fix it to be able to call the methods anyware?


Solution

  • It's not clear exactly what you're trying to accomplish based on the description, but I'll try to answer based on the title, how to emit from a nested child component?

    First, let's cover some

    If you want to use an emit with a deeply nested component, you can pass a mitt instance into the 'provide' context and add the emit listener. Then the child component can use the emitter from the injected instance to notify of an event.

    simple example using mitt

    // parent
    import { provide } from 'vue'
    import mitt from 'mitt';
    
    setup() {
      const bus = mitt();
      bus.on('my-event', ()=>{'do stuff'});
      provide('bus', bus);
    }
    
    // child
    import { inject } from 'vue'
    
    setup() {
      const bus = inject('bus');
      bus.emit('my-event', 'optional parameter');
    }