vue中router.beforeEach()死循环

背景

逻辑是判断访问设备是PC还是移动设备,想如果是移动设备就屏蔽访问,PC则通行。

死循环

router.beforeEach((to, from, next) => {
  if (!isMobile()){ // PC端访问
    console.log("PC端访问")
    if (to.path !== '/login' && to.path !== '/register' && !isLogin()) {
      return next('/login')
    }
    next()
  }
  else {
    console.log("移动设备")
    next('/tip')
  }
})

结果报错栈溢出:

RangeError: Maximum call stack size exceeded

原因

因为 next('/tip') 会在进入前 又要进入beforeEach中 ,这样就会一直循环下去,所以就是想如何跳出这个循环即可

修改

router.beforeEach((to, from, next) => {
  if (!isMobile()){ // PC端访问
    console.log("PC端访问")
    if (to.path !== '/login' && to.path !== '/register' && !isLogin()) {
      return next('/login')
    }
    next()
  }
  else {
    console.log("移动设备")
    if (to.path == '/tip'){  //关键所在:如果要跳转的路径是/tip才放行
      next()
    }
    else {
      next('/tip')
    }
  }
})

效果:

猜你喜欢

转载自blog.csdn.net/qq_33189961/article/details/122161174