hrishikeshpaul
hrishikeshpaul

Reputation: 469

Advanced Vue router guards

So, I have my routers set up like this:

const routes = [
  {
    path: '/',
    name: 'HomePage',
    component: HomePage,
    beforeEnter: checkAuth,
    meta: {
      requiresAuth: false,
      showSidebar: false
    }
  },
  {
    path: '/feed',
    name: 'FeedPage',
    component: FeedPage,
    beforeEnter: checkAuth,
    beforeRouteEnter: ((to, from, next) => {
      console.log(from)
    }),
    meta: {
      requiresAuth: true,
      showSidebar: true
    }
  },
  {
    path: '/faq',
    name: 'FAQPage',
    component: FAQPage,
    beforeEnter: checkAuth,
    meta: {
      requiresAuth: true,
      showSidebar: true
    }
  },
 }
]

So checkAuth is a function that basically checks wether the user is authenticated before Entering that route (using google auth), which works perfectly. But I also want to use beforeRouteEnter to check whether the user's designation is allowed in that route AFTER authentication. I have the designation stored in the Vuex store.

How can I use this keyword such that I can use the plugins?

And also, what is the proper way to use beforeRouteEnter?

Upvotes: 1

Views: 1351

Answers (2)

Andres Abadia
Andres Abadia

Reputation: 833

beforeEnterand beforeRouteEnter are both guards with the same goal, the difference is where to use it.

beforeEnter is a guard you can define on a route's configuration object. https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard

beforeRouteEnter is a guard you define on your component. https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards

Either way if you want to access you Vuex Store you should import it. This could be an Example of your FeedPage component usign beforeRouteEnter

<script>
import Store from '../vuexstore.js'
export default{
  beforeRouteEnter(to,from,next){
    if(Store.state.isAllowed){ 
      next() 
    } else { 
      next(false) 
    }                 
}
</script>

Don't forget to use next() to continue the navigation after the validation.

Upvotes: 0

Emad Dehnavi
Emad Dehnavi

Reputation: 3451

Based on the Vue Router documentations, The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.

However, you can access the instance by passing a callback to next. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument:

beforeRouteEnter (to, from, next) {
  next(vm => {
     // access to component instance via `vm`
  })
}

Also there are beforeRouteUpdate & beforeRouteLeave you might want use as well based on your needs, for these this is available ( but passing callback is not supported on these two )

Upvotes: 1

Related Questions