[Vuejs]-Router.beforeEach in laravel 5.4

0👍

The way to check if the current route requires authentication is documented here: https://router.vuejs.org/en/advanced/meta.html

Change your beforeEach method to this:

router.beforeEach((to,from,next) => {
  if(to.matched.some(record => record.meta.requiresAuth)){
    // do something
  } 
  next();
} 

0👍

As mentioned in the Documentation,

All route records matched by a route are exposed on the $route
object (and also route objects in navigation guards) as the
$route.matched Array. Therefore, we will need to iterate over
$route.matched to check for meta fields in route records.

router.beforeEach((to,from,next) => {
    if(to.matched.some(record => record.meta.requiresAuth)){
        authUser = '';
        const authUser = JSON.parse(window.localStorage.getItem('authUser'))
        if(authUser && authUser.access_token){
            next()
        }else{
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        }
    }
    next()
})

0👍

I just switched the position of router.beforeEach to be before

const app = new Vue({
  el: '#app',
  router,
});

So, in full, the code looks like this:

import router from './routes.js';
require('./bootstrap');

router.beforeEach((to,from,next) => {
  if(to.matched.some(record => record.meta.requiresAuth)){
    const authUser = JSON.parse(window.localStorage.getItem('authUser'))
    if(authUser && authUser.access_token){
      next()
    }else{
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  }
  next()
})

const app = new Vue({
  el: '#app',
  router,
});

Leave a comment