Vue-router: Question: Accessing root's $data in beforeEach hook

Created on 19 Oct 2015  路  5Comments  路  Source: vuejs/vue-router

I'd like to check/use some data from the root (App) component in a beforeEach hook, something like the logged-in user or the state of authentication. I've come up with this:

this.router.app.user

Is this the right way to do?

Most helpful comment

From here

router.beforeEach(async (to, from, next) => {
    await Vue.nextTick()
    console.log(router.app.loggedInUser);
  if (to.path != '/login' && !router.app.loggedInUser) {
    next('/login');
    return;
  }
  next();
})

All 5 comments

router.beforeEach(function () {
  // router.app.user
})

router.app.user doesn't seem to work anymore. Anyone have a workaround?

i have the same problem. i am not sure what is going on. if i log router.app and inspect in chrome i can click and unfold the user object, but if i try to access it in the code it is undefined ?

edit: ah, i guess as it is not yet loaded, but when the inspector has access to the reference it has been populated. that is, when refreshing the browser.. my root app wasnt loaded and therefor the user object wasnt populated yet. so i wonder if there is any way to wait until the app data is populated hmm

i have the same problem. i am not sure what is going on. if i log router.app and inspect in chrome i can click and unfold the user object, but if i try to access it in the code it is undefined ?

edit: ah, i guess as it is not yet loaded, but when the inspector has access to the reference it has been populated. that is, when refreshing the browser.. my root app wasnt loaded and therefor the user object wasnt populated yet. so i wonder if there is any way to wait until the app data is populated hmm

Anything on this??

From here

router.beforeEach(async (to, from, next) => {
    await Vue.nextTick()
    console.log(router.app.loggedInUser);
  if (to.path != '/login' && !router.app.loggedInUser) {
    next('/login');
    return;
  }
  next();
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

baijunjie picture baijunjie  路  3Comments

posva picture posva  路  3Comments

gil0mendes picture gil0mendes  路  3Comments

marcvdm picture marcvdm  路  3Comments

posva picture posva  路  3Comments