[Vuejs]-Vue.js: addRoutes method with array from API call

0👍

You can use addRoutes in this way:

import router from '@/router'
import Project from './pages/Project'
import Projects from './pages/Projects'

router.addRoutes([{
  path: '/projects',
  name: 'projects.projects',
  component: Projects,
  props: false
}, {
  path: '/projects/:id',
  name: 'projects.project',
  component: Project,
  props: true
}])

From docs:

Dynamically add more routes to the router. The argument must be an Array using the same route config format with the routes constructor option

Full example:

You have the main router like this:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../components/pages/Home';

Vue.use(VueRouter);

const router = new VueRouter({
 mode: 'history',
 routes: [
  {
   path: '/home',
   name: 'home',
   component: Home,
  },
  ],
});

export default router;

Now, you create a new page with the following structure.

-- NewPage
   -- NewPage.vue
   -- route.js

The route.js should look like this:

import router from '@/router' //importing the main router
import NewPage from './NewPage.vue'

router.addRoutes([
  {
    path: '/new-page',
    name: 'newPage',
    component: NewPage,
  },
])

Hope I helped you.

Leave a comment