3

I'm trying to nest routes with the VueJS router (next/4.x) so that the child route completely replaces the parent component.

The example given here assumes that for each sub route, there's a sub component being rendered, but I'd like to replace the component User entirely when navigating to /user/johnny/profile instead of rendering Profile within the User component.

/user/johnny/profile                     /user/johnny/posts
+------------------+                  +-----------------+
| User             |                  | User            |
| +--------------+ |                  | +-------------+ |
| | Profile      | |  +------------>  | | Posts       | |
| |              | |                  | |             | |
| +--------------+ |                  | +-------------+ |
+------------------+                  +-----------------+

I tried to omit the <router-view> tag in User, but that just doesn't render Profile when navigating to /user/johnny/profile (most likely because it doesn't find a place to render the Profile component).

The only thing that seems to be working is to check the route name in UserComponent and hide <router-view> when the route is /user/johnny or hide the markup for UserComponent and just show <router-view when the child route is active. I wonder if there's a better way to do this. For instance, it would be nice if the <router-view> could just be removed and the ProfileComponents finds the next closest parent's <router-view> to render itself, but I haven't found ways to configure this or examples that would suggest that's possible...

orange
  • 7,755
  • 14
  • 75
  • 139

1 Answers1

0

What you need to is to create both the Profile and Posts components as childlren routes to user's route.

So, in the user's component, you only need to define the in the template's tag.

Example:

route.js

const routes = [
  {
    path: '/user',
    name: 'user',
    component: UserComponent,
    children: [
      {
        path: '/profile',
        name: 'user-profile',
        component: UserProfileComponent
      },
      {
        path: '/post',
        name: 'user-post',
        component: UserPostComponent
      }
    ]
  }
]

UserComponent.vue

<template>
  <router-view />
</template>
Jelil Adesina
  • 277
  • 3
  • 7