简体   繁体   中英

Vue.js: addRoutes method with array from API call

I am going to use the addRoutes method for the first time. I didn't find any full tutorials of how developers can use this method so I decided to try and ask here.

In my app I have some sort of CMS so a user can create new pages with custom paths. In my router/index.js file where I import components and declare their routes I need to add these custom routes.

I have an API endpoint which can give me a JSON with arrays of these routes. How can I call this endpoint in my router/index.js file and add these new routes to my router?

Here is what I have in my router.index.js file (I added its structure rather than code itself):

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

Vue.use(VueRouter);

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

router.addRoutes([]);

export default router;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM