Search code examples
vue.jsvuejs3vue-router

Why does Vue router require an empty path child route to be named in order to render?


I have a route setup where there's a parent with child routes, like this:

{
    //name: 'ProductComments',
    path: 'comments',
    children: [
        {
            name: 'ProductComments',
            path: '',
            component: ProductComments
        },
        {
            name: 'EditProductComment',
            path: ':commentId/edit',
            component: EditProductComment
        }
    ]
}

With the above configuration, Vue Router will render my ProductComments component if I visit /comments. However, if I comment the name out and uncomment it on the parent, it won't render the ProductComments component and will give me the warning:

The route named "ProductComments" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.

But why is this? The child is always a more "specific" route, so why does giving it a name magically cause it to render, whereas giving the name to the parent stops it?


Solution

  • I think this is one of those things that was decided by the Vue team and only they can really answer why. I was curious about it though and found this github thread talking about the exact same thing. Doesn't seem like a satisfactory answer was ever found but the comment I specifically linked contains a workaround which is just adding a redirect:

    { 
          path: '/user/:id', 
          name: 'user',
          /* Explicitly tell the router to redirect to default children */
          redirect: '/user/:id/',
          component: User,
          children: [
            { 
              path: '', 
              component: UserProfile 
            },
            { 
              path: 'posts', 
              component: UserPosts
            }
          ]
    }