Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`this` undefined in vue-router beforeEach

Tags:

I'm trying to access the session in vue-router viathis.a.app, but it pops out 1 error. After i debug, i found out that this is undefined. this is the code im using to show this.

I had tried to use function(to, from, next) {...} instead of es6 syntax, but this is still undefined.

router.beforeEach((to, from, next) => {
  if (!to.meta.isPublic){
    // eslint-disable-next-line
    console.log(this)
  }
  next()
})

Is there any configuration i need to make so that i can access this in vue-router?

like image 956
Tan Vee Han Avatar asked Oct 18 '19 02:10

Tan Vee Han


People also ask

What is VUE router hash mode?

The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. To get rid of the hash, we can use the router's history mode, which leverages the history.

Can we define multiple router outlets in a component Vue?

Instead of having one single outlet in your view, you can have multiple and give each of them a name. A router-view without a name will be given default as its name. A working demo of this example can be found here.

Does Vue router destroy component?

If we do not force Vue Router 4 to destroy the current component when we're navigating to another route, it will reuse the same component and not re-fire the created hook. We also get the user profile form saving data to the Firestore.


1 Answers

Yes, you can use access "this" inside router beforeEach hook, but in a different way. The router has the root instance from where it is inserted

User router.app it is pointing to "this" (the root Vue instance)

 router.beforeEach((to, from, next) => {
  if (!to.meta.isPublic){
    // eslint-disable-next-line
    console.log(router.app)
  }
  next()
})
like image 147
chans Avatar answered Nov 14 '22 21:11

chans