1

I have a routing:

{
    path: '/user',
    name: 'user',
    component: () => import('@/views/users/Users.vue'),
    children: [
        {
        path: '/:id/:username?',
        name: 'userData',
        component: () => import('@/components/users/User.vue'),
        },
    ],
},

My setting router:

const router = new VueRouter({
   mode: 'history',
   base: process.env.BASE_URL,
   scrollBehavior: () => ({ y: 0 }),
});

I have a problem with child element in route. When I go to the site http://localhost:8080/user I see list with all user from databse. But when i go to the site: http://localhost:8080/user/1/john vue loads view again with all user (view Users.vue), here I need load component with data of one user (component User.vue). Parameter username is optinal.

michal
  • 1,534
  • 5
  • 28
  • 62
  • 1
    Have you checked this? https://github.com/vuejs/vue-router/blob/dev/examples/route-matching/app.js From `http://localhost:8080/user/1/john` it goes with `/:id/:username` since you didn't assign a component for that route, it inherits parent component `Users.vue` – SC Kim Apr 23 '20 at 11:25
  • 1
    You must create two routers without parent/children. – Gabriel Willemann Apr 23 '20 at 11:40
  • https://stackoverflow.com/questions/47824660/optional-param-in-vuejs-router Adding this existing thread as another reference. – SC Kim Apr 23 '20 at 11:47
  • 1
    Try removing the first slash char in `/:id/:username?`. – Yom T. Apr 23 '20 at 11:59

1 Answers1

3

The problem is you are adding / prefixed children route. The documentation clearly says that

Note that nested paths that start with / will be treated as a root path. This allows you to leverage the component nesting without having to use a nested URL.

You should rewrite the children route as given and it should work.

children: [
    {
        path: ':id/:username?',
        name: 'userData',
        component: () => import('@/components/users/User.vue'),
    },
],

You can only add / to the root routes. any route that is written starting with slash will be treated as root route in vue-router.

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81