vue 首次加载项目,控制台报错: Redirected when going from "/" to "/login"

第一次加载加载页面时报错如下:
Redirected when going from "/" to "/login" via a navigation guard.
image.png

后续在地址栏直接添加/login,index,错误页面等均正常无报错.

路由配置如下:

router.beforeEach((to, from, next) => {
    if (token) {
        if (to.path == '/login') {
            next('/index')
        } else if (to.path === null) {

            next('*')
        } else {
            next()
        }
    } else {
        if (to.path == '/login') {
            next()
        } 
    }

})

还会出现路由无限循环跳转的情况.
请求大家的帮助.

阅读 22.6k
7 个回答
import Router from 'vue-router'

const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
if (token) {

    } else {
        if (to.path == '/login') {
            next()
        } 
    }
新手上路,请多包涵

你好有解决吗?我这边也存在这样的问题,请教下

新手上路,请多包涵

请问你这个无限循环解决了么?

目前我已知的会产生循环路由的是next(to)这个方法,直接next()不会产生循环。但是观察楼主这些代码似乎不存在这个问题

router.beforeEach((to, from, next) => {

  const isLogin = !!localStorage.eleToken

  if (to.path === '/login') {

    next()

  } else {

    isLogin ? next() : next('/login')

  }

})
推荐问题