Vue使用addRoute动态添加权限路由,页面刷新重定向404的问题

650 阅读1分钟

在beforeEach里使用addRoute动态添加的权限路由

await store.dispatch("setUserInfo", userData.data);
        let userInfo = store.state.user.UserInfo;
        const currentRoutes: any = router.options.routes; // 初始路由
        const asyncRoutes: any = userInfo.routes; // 权限路由

        if (hasRoles) {
          const Permission = userInfo.Permission; // 角色权限
          asyncRoutes.forEach((item: any) => {
            if (item.meta.isShow.includes(Permission)) {
              router.addRoute("home", { ...item });
              currentRoutes[0].children.push(item);
            }
          });
          hasRoles = false;
          next({ ...to, replace: true });
        }

然后在固定路由里设置了重定向到动态路由,导致刷新页面直接空白并报错:Uncaught RangeError: Maximum call stack size exceeded。

原因

这是因为重定向的时候动态路由还没有配置。

{
    path: "/",
    name: "home",
    redirect: "/order",
    component: () => import("../components/Home/index.vue"),
    children: [],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/404",
    name: "404",
    component: () => import("../views/NoResponse.vue"),
  },
  {
    path: "/:catchAll(.*)",
    redirect: "/order",
  },

解决方案:

不要在固定路由里设置重定向,把它放到动态路由之后,然后router.addRoute就好了

if (hasRoles) {
          const Permission = userInfo.Permission; // 角色权限
          asyncRoutes.forEach((item: any) => {
            if (item.meta.isShow.includes(Permission)) {
              router.addRoute("home", { ...item });
              currentRoutes[0].children.push(item);
            }
          });
          hasRoles = false;
          router.addRoute({
            path: "/:catchAll(.*)",
            redirect: "/order",
          });
          next({ ...to, replace: true });
        }