在应用 运行 时将路由添加到 Vue.js 路由器

Add route to Vue.js router while app is running

我目前正在构建一个应用程序,我想为这个应用程序添加扩展。这些扩展应该有自己的 Vue 组件和视图(因此也有路由)。我不想重建应用程序,而是动态添加新视图和路由。有没有用 Vue 2 做到这一点的好方法?

在下面我添加了一些文件,希望能使这个问题更容易理解。 router/index.js 包含基本结构,并以常规方式添加到 main.js 文件中。在 app.vue 加载期间,应加载新路由并将其附加到现有路由。

路由器

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>

我使用短语 <add route to router> 来演示我想要添加路由的方式。添加路由后,用户应该能够使用 <router-link to="/test">Test</router-link>.

直接导航到新视图

如有任何帮助,我们将不胜感激。

使用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.

router 导入 App.vue 以使用它:

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>