【问题标题】:Getting error while adding new routes, path is required in a route configuration添加新路由时出错,路由配置中需要路径
【发布时间】:2021-07-27 10:24:11
【问题描述】:

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

[vue-router] 路由配置中需要“路径”。

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

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>

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-router


    【解决方案1】:
    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>

    【讨论】:

    • 当我尝试再次渲染相同的路线时,我遇到了新问题,现在它显示为 [vue-router] Duplicate named routes definition:
    猜你喜欢
    • 2013-01-02
    • 2018-01-03
    • 2019-11-15
    • 1970-01-01
    • 2012-09-28
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多