I want to emit an event on the root component, and listen to in in the root component. In a child of child component I do this:
this.$root.$emit('access-token', accessToken);
In root component (the top component, first to load) I do this (edit: this is in the mounted() method):
this.$on('access-token', this.setAccessToken);
It doesn't react to the event though. Why?
$root. emit emits an event from the root component. this. $emit simply emits an event from the current component.
Vue $emit is a function that lets us emit, or send, custom events from a child component to its parent. In a standard Vue flow, it is the best way to trigger certain events.
Accessing the Root Instance In every subcomponent of a new Vue instance, this root instance can be accessed with the $root property. For example, in this root instance: // The root Vue instance.
You are not using the $root
for the event $on
Change this:
this.$on('access-token', this.setAccessToken);
for this:
this.$root.$on('access-token', this.setAccessToken);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With