Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 811
Mattias Avatar asked May 04 '18 19:05

Mattias


People also ask

What is this root emit?

$root. emit emits an event from the root component. this. $emit simply emits an event from the current component.

What are emits in Vue?

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.

What is $root in Vue?

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.


1 Answers

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);
like image 59
Andres Garcia Avatar answered Sep 28 '22 16:09

Andres Garcia