Navigation guard using Vue router - infinite loop problem

H⃰U⃰A⃰ 2021-09-15 09:16:50

I used the global guard in the project ,beforeEach, Easy to manage
But there was a problem , Is in the beforeEach() The problem of infinite cycle appears after the judgment condition is set
The code at that time was as follows :

router.beforeEach((to, from, next) => {
if (isLogin) {
next()
} else {
console.log(' test ')
next('login')
}
})

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

result chrome Of debug see :

 Use Vue-Router Navigation guard - Infinite loop problem _router

I understand this question in this way :
next() Indicates the route is successful , Go straight into to route , Never call again router.beforeEach()
next(‘login’) Indicates that the route interception is successful , Redirect to login, Will call... Again router.beforeEach()
in other words beforeEach() Must call next(), Otherwise, there will be infinite cycles ,next() and next(‘xxx’) It's different , The difference is that the former will not call again router.beforeEach(), The latter will !!!
It's written on the official website ( It's mainly the red line !):
 Use Vue-Router Navigation guard - Infinite loop problem _router_02

The final solution is as follows :

router.beforeEach((to, from, next) => {
if (isLogin) {
next()
} else {
if (to.name === 'login') {
next()
} else {
console.log(' test ')
next('login')
}
}
})

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

I think it's helpful for you to like it in the upper right corner ~

 Use Vue-Router Navigation guard - Infinite loop problem _ Navigation guard _03

Scan the QR code above for my subscription number ~
Please bring the original link to reprint ,thank
Similar articles

2021-09-15

2021-09-15