Vue 路由导航 导致栈溢出问题

448 阅读1分钟

需求: Workbench 无限制 其他页面判断code是否存在

router.beforeEach((to, from, next) => {
    if (to.path == '/Workbench') {
        next();
    } else {
        const arr = 'yJhbGcpbiIsImlhdCI6MTY1MDUyMDAyNCw';  //虚拟数据
        if (arr?.code) {
            next();
        } else {
            next('/404');
        }
    }
})

export default router;

错误👇

image.png

解决方案

router.beforeEach((to, from, next) => {
    if (to.path == '/Workbench') {
        next();
    } else {
        const arr = 'yJhbGcpbiIsImlhdCI6MTY1MDUyMDAyNCw';  //虚拟数据
        
     //next('/404')`会一直执行,比如你跳转到 `/home` 发现没有code,然后跳到`/404`,
     然后又再次触发 `beforeEach` 发现还是没有code,继续去 `/404` 。就会一直循环!!
     下面是改正后的方案 👇 
        
        
        if (arr?.code|| to.path == '/404') { 
            next();
        } else {
            next('/404');
        }
    }
})

export default router;

有问题可以在下方留言