Philipp M
Philipp M

Reputation: 522

Add route to Vue.js router while app is running

I'm currently building an app and I would like to add extensions to this app. These extensions should have their own Vue components and and views (and thus also routes). I don't want to rebuild the app but instead add the new views and routes dynamically. Is there a good way to do that with Vue 2?

In the following I added the files that I hope makes this question a bit more comprehensible. The router/index.js contains the basic structure and is added to the main.js file in the regular fashion. During the load of the app.vue the new routes should be loaded and appended to the already existing ones.

router

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/test">Test</router-link>
    </div>
    <router-view/>
  </div>
</template>

<script>
// @ is an alias to /src
import TestView from '@/views/Test.vue'

export default {
  name: 'Home',
    components: {},
    created() {

      <add route to router>({
          component: TestView,
          name: "Test",
          path: "/test"
      })
    }
}
</script>

I used the phrase <add route to router> to demonstrate the way I would like to add the route. After the route is added the user should be able to directly navigate to the new view using <router-link to="/test">Test</router-link>.

Any help would be appreciated.

Upvotes: 5

Views: 4044

Answers (1)

Dan
Dan

Reputation: 63099

Use addRoute to add routes at runtime. Here is the explanation for this method from the docs:

Add a new route to the router. If the route has a name and there is already an existing one with the same one, it overwrites it.

Import the router into App.vue to use it:

App.vue

<script>
import router from './router/index.js';
import TestView from '@/views/Test.vue'

export default {
  created() {
    router.addRoute({
      component: TestView,
      name: "Test",
      path: "/test"
    })
  }
}
</script>

Upvotes: 5

Related Questions