简体   繁体   中英

Infinite Loop with Vue Router Global Before Guards

I'm trying to redirect the user with Firebase Auth and Vue Router.

The point is that when Router redirects the user to '/' nothing is displayed in the website (completely white screen).

I know that I'm doing something wrong, but I don't know exactly what is wrong.

This is how looks like my 'router.js' file:

const router = new Router({
  routes: [
    {
      path: '*',
      redirect: '/login'
    },
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: {
        authenticated: true
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  let user = firebase.auth().currentUser;
  let approbation = to.matched.some(record => record.meta.authenticated)
  if (approbation && !user) {
    next('/login')
  } else if (!approbation && user && from.path !== '/') {
    next('/')
  }
})

export default router 

It could be that neither if (approbation && !user) nor else if (!approbation && user && from.path !== '/') is true. Since you're not calling next() after you if-else block, the hook is never resolved and vue-router doesn't know where to go.

Make sure to add a call to next() after you if-else blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM