Vue3 VueRouter4 动态路由 [Vue Router warn]: No match found for location with path

1,380 阅读1分钟

问题说明

在使用 vue3 vue-router4 在router.beforeEach添加动态路由时候,如果没有配置全局的404路由会报警告[Vue Router warn]: No match found for location with path

解决方式

  1. 添加404配置
  2. 路由拦截器处理
静态路由添加如下配置
// 静态路由配置
  {
    path: "/404",
    component: () => import("@/views/error/404.vue"),
    name: "404",
    // 个性化数据根据实际情况处理
    meta: {
      auth: false,
      title: "404",
    },
  },
  {
    path: "/:pathMatch(.*)",
    name: "notFound",
    redirect: "/404",
  },
路由拦截器做如下处理
let flag = false;
setupDynamicRoute = (router: Router) => {
  router.beforeEach((to, from, next) => {
    try {
      const { accessRoutes } = toRefs(usePermissionStoreWithout());
      const routes = convertComponent(accessRoutes.value);
      if (!flag) {
        // 后端返回的路由表
        routes.forEach((route) => {
          router.addRoute(route);
        });
        flag = true;
        if (to.path === "/404" && to.redirectedFrom) {
          next({ path: to.redirectedFrom.fullPath, replace: true });
        } else {
          next({ ...to, replace: true }); //路由进行重定向放行
        }
      } else {
        next();
      }
    } catch (error) {}
  });
}
分析

核心代码为

if (to.path === "/404" && to.redirectedFrom) {
    next({ path: to.redirectedFrom.fullPath, replace: true });
} else {
   next({ ...to, replace: true });
}

这样处理是因为,第一次路由还未加载完成会报警告 No match found for location with path,第一次访问路由尚未加载完成会重定向到 404,所以我们在这里再做一次转发,使用to.redirectedFrom(包含了重定向之前最初想访问的地址)