search

Home  >  Q&A  >  body text

Vue Router attempts to match routes using params as names.

<p>I am trying to use parameters in my routes and have created the following route. </p> <pre class="brush:php;toolbar:false;">export const ConsumerRoutes = [ { path: '/' import.meta.env.VITE_MODULE_ADMIN_NAME '/consumers', meta: { requiresAuth: true, adminLayout: true, module: 'admin', icon: UserCircleIcon, nav: 'Consumers' }, children: [ { path: '', name: 'Consumers', component: () => import('../../views/admin/Consumer.vue'), }, { path: ':id', name: 'Consumer Details', component: () => import('../../views/admin/ConsumerDetails.vue'), } ], }, // { // path: '/' import.meta.env.VITE_MODULE_ADMIN_NAME '/consumers/:id', // meta: { // requiresAuth: true, // adminLayout: true, // module: 'admin', // excludeFromNav: true // }, // children: [ // { // path: '', // name: 'Consumer Details', // component: () => import('../../views/admin/ConsumerDetails.vue'), // } // ] // } ];</pre> <p>When I try to enter /1 in the URL, I can navigate to consumers, but I get the following error. </p> <pre class="brush:php;toolbar:false;">vue-router.mjs:810 Uncaught (in promise) Error: No match for {"name":"1","params":{}}</pre> <p>However, if I use console.log in the afterEach function to print my target route, I get the following route object. </p><p>So it knows which route I'm going to, but for some reason it's using '1' trying to find a route named '1'. If I change my route name to 1 it loads fine. </p><p>I've tried splitting my routes from child routes to independent routes but that didn't change anything. </p><p><br /></p> <hr /> <p>The problem has been solved and has nothing to do with the routes I defined. </p>
P粉826429907P粉826429907489 days ago697

reply all(1)I'll reply

  • P粉817354783

    P粉8173547832023-07-28 15:48:22

    The problem you are experiencing may be because Vue Router is trying to match based on the name of the route instead of the path.

    You are trying to navigate to /consumers/1, expecting "1" to be a route parameter (:id). But Vue Router interprets "1" as the route name, hence the error message you see.

    Make sure you navigate using the route path and not the route name. In your afterEach hook, use the following code:


    router.afterEach((to, from) => {
      router.push(to.path);
    });

    When navigating manually, use the path ('/consumers/1'), not the name. If you're still having problems, it's probably due to another part of your code.

    The following is sample code for navigating to a route by name:


    router.push({ name: 'Consumer Details', params: { id: 1 } })

    Also, here is sample code for navigating to a route by path:

    router.push('/consumers/1')

    Should be useful

    reply
    0
  • Cancelreply