Home » vue » Separate VueJS children routes

Separate VueJS children routes

Posted by: admin November 26, 2021 Leave a comment

Questions:

Here is my router.js code:

const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: {
        title: app.NAME + ' | ' + pages_title.LOGIN_PAGE
      }
    },
    {
      path: '/',
      component: DashboardView,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          component: Dashboard,
          name: 'Dashboard',
          meta: { title: app.SMALL_NAME + ' | ' + pages_title.DASHBOARD_PAGE }
        },

        // PRODUCTS START
        // INDEX
        // SHOW
        {
          path: 'product/details/:product_id',
          component: ProductDetails,
          name: 'ProductDetails',
          meta: { title: app.SMALL_NAME + ' | ' + pages_title.PRODUCTS_SHOW_PAGE}
        },
      ]
    }
  ]
});

What I am trying to do:

This code runs good but I am trying here to find the best practice and separate my children routes.

I want to separate the SHOW route and “INDEX” route in a separated file..

What I have tried to do:

I have created a products_routes.js and I have added this code to it.

    let products_routes = [
  {
    path: 'products',
    component: Products,
    name: 'Products',
    meta: { title: app.SMALL_NAME + ' | ' + pages_title.PRODUCTS_PAGE }
  }
];

export default products_routes;

And I have included this file in my main router.js file..

How I inject that code in my router.js file after importing it?

I have tried to do this:

import products_routes from '@/routes/products_routes';
const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: {
        title: app.NAME + ' | ' + pages_title.LOGIN_PAGE
      }
    },
    {
      path: '/',
      component: DashboardView,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          component: Dashboard,
          name: 'Dashboard',
          meta: { title: app.SMALL_NAME + ' | ' + pages_title.DASHBOARD_PAGE }
        },

        // PRODUCTS START
        // INDEX
        products_routes[0], // HERE I INJECTED MY products routes
        // SHOW
        {
          path: 'product/details/:product_id',
          component: ProductDetails,
          name: 'ProductDetails',
          meta: { title: app.SMALL_NAME + ' | ' + pages_title.PRODUCTS_SHOW_PAGE}
        },
      ]
    }
  ]
});
Answers:

@Dill you can use the same method, and idea is to create different “bundles” separated by categories/groups and do something like modules in vuex:

import authRoutes from '@/routes/bundles/authRoutes';
import dashboardRoutes from '@/routes/bundles/dashboardRoutes';
import productRoutes from '@/routes/bundles/productRoutes';

const router = new Router({
  routes: [
   ...authRoutes,
   ...dashboardRoutes,
   ...productRoutes,
  ]
});