'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 1:[1]
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
- The vue3 event emitting is tied to the components, so you could use the event bubbling equivalent of prop drilling, but this not a very robust solution.
- Vue3 no longer includes an event bus (like it did in Vue2), so you need to rely on a 3rd party library (like mitt) for event subscription
- You can use provide/inject to make a variable available between a parent and any nested component.
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');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel |
