user8174757
user8174757

Reputation:

Vue js separate routes in different files

I am creating a single page app and i would like to separate the route files in different files

Thta is in my main routing file index.js i have

export default new Router({
 routes: [
   { path: '/', component: Hello },
   {path :'/users', component: UsersContainerComponent,
       children:[
           {path :'', component: UsersComponent},
           {path :'/create', component: UsersCreateComponent},
           {path :'/update', component: UsersUpdateComponent},

         ]
      },

] })

Now i have other functionalities included not only the users alone hence the code becomes huge, How can i outsource the users routing functionality in another file and only include the reference to the main routes file

So how can i achieve something like this

export default new Router({
  routes:[
    {path:'users', .....}// here load users routing in another file

    ]
  })

as this will make the code more readable and manageable.

Upvotes: 9

Views: 13512

Answers (2)

Eliram
Eliram

Reputation: 131

I liked disjfa solution: Let’s route a vue app component route

import People from '../views/People';
import Welcome from './../views/Welcome';
import Details from './../views/Details';
import Create from './../views/Create';

export default [
  {
    path: '/people',
    name: 'people',
    component: People,
    title: 'People',
    redirect: { name: 'people-welcome' },
    children: [
      {
        path: 'welcome',
        name: 'people-welcome',
        component: Welcome,
      },
      {
        path: 'create',
        name: 'people-create',
        component: Create,
      },
      {
        path: ':id',
        name: 'people-details',
        component: Details,
      },
    ],
  },
];

main route

import Vue from 'vue';
import Router from 'vue-router';
import Dashboard from '@/views/Dashboard';
import peopleRoutes from '@/modules/people/router';

Vue.use(Router);

const baseRoutes = [
   ...
];

const routes = baseRoutes.concat(peopleRoutes);
export default new Router({
  routes,
});

Upvotes: 13

Lassi Uosukainen
Lassi Uosukainen

Reputation: 1688

You can add children to a route in your main route file.

{
  path: '/events',
  component: eventspage,
  children: eventroutes,
},

Inside the child routes component you can do the following:

const eventroutes = [
  {
    path: '',
    name: 'eventlist',
    component: eventlist,
  },
  {
    path: 'info/:id',
    name: 'eventlist',
    component: eventlist,
  },
];

export default eventroutes;

Basically, you can directly take out the routes inside the children part and make them a separate file.

Upvotes: 5

Related Questions