vue路由守卫报错 Error: Redirected * to * via a navigation guard.

wgf4242
  • 90
// router.ts
const routes: Array<RouteConfig> = [
    {path: '/', redirect: {name: 'Home'}},
    {path: '/home', name: 'Home', component: Home},
    {
        path: '/dashboard', component: () => import('../views/Dashboard.vue'),
        meta: {isLogin: true},
        children: [
            {path: '', component: () => import('../views/Dash/Certificate/index.vue'), meta: {isViewer: true},
            {path: 'profile', component: () => import('../views/Dash/ProfileComponent.vue')},
        ]
    },
];


//guard
router.beforeEach((to, from, next) => {
    const profilePath = "/dashboard/profile";
    if (!to.matched.some(res => res.meta.isLogin)) {
        return next();
    }

    // isNotLogin
    if (!localStorage['currentUser'])
        return next({path: "/", query: {redirect: to.fullPath}});

    // isLogin
    if (to.matched.some(res => res.meta?.isViewer)) {
        viewService.isCertificateViewer ? next() : next({path: profilePath})
    } else next()
});

直接访问/dashboard,不是viewer权限,next到 /dashboard/profile。然后就报错了

vue-router.esm.js:1958 Uncaught (in promise) Error: Redirected when going from "/home" to "/dashboard" via a navigation guard.

回复
阅读 4.8k
2 个回答
KenOscar
  • 866

这里是因为一个从一级路由跳转到二级路由的path路径问题

重复的重定向引起vue-router报错。。

在跳转前判断当前页面是否就是要跳转的页面,如果是则不再次跳转,这样就不会报错了

wgf4242
  • 90

我改了下好像不行, 在最上面改的。。之前太丑了。重写了下。

宣传栏