Home  >  Q&A  >  body text

Routing configuration error, need to specify the path

<p>I want to add dynamic routes and use the same component in all dynamic routes. I tried the following code to render the component, but I got an error with the following error message: </p> <blockquote> <p>[vue-router] "path" is required in routing configuration. </p> </blockquote> <p>What is the correct way to add dynamic routing and display the same component? </p> <p> <pre class="brush:js;toolbar:false;">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]) }, } });</pre> <pre class="brush:html;toolbar:false;"><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></pre> </p>
P粉113938880P粉113938880397 days ago410

reply all(1)I'll reply

  • P粉754473468

    P粉7544734682023-08-29 12:38:14

    1. The main problem is that you pass the array to the addRoutefunction
    2. The second problem is the missing / at the beginning of the path (without it you will get a "Non-nested routes must contain a leading slash character" error)
    3. Finally use$router.pushJump to the new route

    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>

    reply
    0
  • Cancelreply