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

tuwxkamq  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(413)

我想添加动态路由,并对所有动态路由使用相同的组件。我尝试了以下代码来渲染组件,但我得到的错误是:
[vue路由器]“路径”在路由配置中是必需的。
添加动态管线和显示相同组件的正确方法是什么?

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>
dluptydi

dluptydi1#

主要问题是您正在将数组传递到 addRoute 第二个问题缺失 / 在路径的开头(如果没有它,则会出现“非嵌套管线必须包含前导斜杠字符”错误)
最终使用 $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>

相关问题