I recently set up mitt and I'm facing difficulties dispatching events to another component. The issue arises due to the absence of this
in the setup()
method, making it challenging to access the app instance.
Here's my current approach:
import App from './App.vue'
const el = document.getElementById('app')
import mitt from 'mitt';
const emitter = mitt();
const app = createApp(App)
app.config.globalProperties.emitter = emitter;
app.mount(el);
In the desired component, I aim to dispatch an event
export default {
setup() {
function toggleSidebar() {
this.emitter.emit('toggle-sidebar');
console.log(this); // binds to setup(), not the vue instance.
}
}
}
Due to the absence of this
, accessing .emitter
is not possible. What am I overlooking? How can I effectively utilize mitt in Vue 3 Composition API?
Interestingly, using v2 syntax allows me to access this.emitter
. However, I'm keen on exploring the Composition API method.
export default {
mounted() {
console.log(this.emitter); // works
}
}