IMG-LOGO

How to combine multiple path route files in Vue.js?

andy - 15 May, 2018 16494 Views 5 Comment

If you build a complex application in Vue.js, you may wonder how you can split route paths into multiple files. The idea is not to place and manage all the routes into one single file. It will definitely be a nightmare to manage and handle the routes. This is why by placing a router file to each individual system or module will make your life easier to manage your app.

Let assume we have two separate route files that we want to combine into the main route. Please see the following example structure of the sample Vue.js app I create.

Each of the router.js file will represent individual path for each folder which can be considered as a module or sub system if you want to say. Here is the code for router 1 file.

import Main from '@/components/Admin/Main'

const routes = [
  {
    path: '/admin',
    name: 'Main',
    component: Main
  }]

export default routes

Here is the code for router 2 file.

import Login from '@/components/Shared/Login'
import Register from '@/components/Shared/Register'
import ForgotPassword from '@/components/Shared/ForgotPassword'

const routes = [
  {
    path: '/',
    alias: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: ForgotPassword
  }]

export default routes

To combine the code is pretty simple. What you need to do is to create an array variable and using the built in javascript concat to combine the exported router classes. Here is the full code of the main router file.

import Vue from 'vue'
import Router from 'vue-router'
import SharedRoutes from '@/components/Shared/Router'
import AdminRoutes from '@/components/Admin/Router'

Vue.use(Router)

var allRoutes = []
allRoutes = allRoutes.concat(SharedRoutes, AdminRoutes)

const routes = allRoutes

export default new Router({
  routes
})

Pretty simple right? Feel free to post your question below if you have any question.

Comments

Ermal
04 Mar, 2019
Thank you for this really helpful article. It is a very simple, elegant and powerful solution.
René Cadenas
26 May, 2019
Thank you for sharing. :D
Fabricio Zeferino
04 Sep, 2019
Like that works nice for me: const routes = [... SharedRoutes, ... AdminRoutes];
Lars Schinkel
02 Oct, 2019
Thank you andy. Fabricio as well. Nice and sleek solution.
albert
09 Mar, 2021
This method doenst work with children routes.
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles