添加新路由时出错,路由配置中需要路径

Getting error while adding new routes, path is required in a route configuration

我想添加动态路由并为所有动态路由使用相同的组件。我已尝试使用以下代码来呈现组件,但出现错误消息:

[vue-router] "path" is required in a route configuration.

添加动态路由并显示相同组件的正确方法是什么?

const Foo = {
  template: '<div>Foo</div>'
}
const Home = {
  template: '<div>Home</div>'
}

const router = new VueRouter({
  mode: 'history',
  routes: [{
    path: '/',
    component: Home
  }]
})
const app = new Vue({
  router,
  el: "#vue-app",
  methods: {
    viewComponent: function(path, method) {
      debugger;
      let tf = `${path}/${method}`;

      let newRoute = {
        path: tf,
        name: `${path}_${method}`,
        components: {
          Foo
        },
      }
      this.$router.addRoute([newRoute])

    },

  }


});
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="vue-app">
  <a v-on:click="viewComponent('api/contact','get')">ddd</a>

  <router-view></router-view>
</div>

  1. 主要问题是您将数组传递给 addRoute
  2. 第二个问题在路径的开头缺少/(没有它,你会得到一个“非嵌套路由必须包含前导斜杠字符”的错误)
  3. 终于用$router.push去新的路线

const Foo = {
  template: '<div>Foo</div>'
}
const Home = {
  template: '<div>Home</div>'
}

const router = new VueRouter({
  mode: 'history',
  routes: [{
    path: '/',
    component: Home
  }]
})
const app = new Vue({
  router,
  el: "#vue-app",
  methods: {
    viewComponent: function(path, method) {
      let tf = `/${path}/${method}`;

      let newRoute = {
        path: tf,
        name: `${path}_${method}`,
        component: Foo,
      }
      this.$router.addRoute(newRoute)
      this.$router.push({ name: newRoute.name })
    },
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="vue-app">
  <a v-on:click="viewComponent('api/contact','get')">ddd</a>

  <router-view></router-view>
</div>