this.$root.$emit not working in Vue

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?

Answers:

Answer

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);
Answer

I've to use the following approach:

mounted() {
  this.$nuxt.$emit('event-name')
} 
mounted() {
  this.$nuxt.$on('event-name', () =>
    ...
  }
}

Using Nuxt 2.14

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.