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

Time:04-16

I need to detect parent route /products from inside of the FeaturedProducts.vue component. Which has a route path of /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')           
      }
    ]
  }];

How can I find the parent route programmatically in a component?

CodePudding user response:

You can get all routes using router.getRoutes() and iterate to check if child routes matches your current route.

 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;
   }
 }
  • Related