如何在组件中查找当前路由的父路由信息

How to find parent route info of the current route within a component

我需要从 FeaturedProducts.vue 组件内部检测父路由 /products。其路由路径为 /product-list/featured

const routes = [
  {
    path: "/",
    name: "Home",
    component: () => import('./Home.vue')   
  }, 
  {
    path: "/product-list",
    name: "Products",
    component: () => import('./Products.vue'),      
    children: [
      {
        path: '/featured',
        name: "FeaturedProducts",
        component: import('./FeaturedProducts.vue')           
      }
    ]
  }];

如何以编程方式在组件中找到父路由?

您可以使用 router.getRoutes() 获取所有路由并迭代检查子路由是否与您当前的路由匹配。

 setup() { 
   const router = useRouter();

   function findParentRoute() {
     let found = null;
     router.getRoutes().forEach((r) => {
       (r.children || []).forEach((ch) => {
         if (r.path + "/" + ch.path == route.path) {
           found = r;
         }
       });
     });
     return found;
   }
 }

注意

此解决方案仅在 full-paths 匹配时有效。如果路径有参数,您可以使用 route.name 而不是 route.path