can't navigate to nested route but browser url gets updated

Viewed 422

I have some simple CRUD pages for users (and use Vuetify). So

  • /users will render the users list
  • /users/:id will render the user profile

After setting up my nested routes in the router config I'm navigating to those nested routes but my currently rendered view doesn't update although the browser url gets updated. Steps to reproduce:

  1. Create a new Vue project with Vue Router
  2. Add Vuetify to the project
  3. Update the App.vue file to

.

<template>
  <v-app>
    <router-view></router-view>
  </v-app>
</template>
  1. Create a users view

.

<template>
  <v-btn to="/users/1">Navigate</v-btn>
</template>
  1. Create a user view

.

<template>
  <p>User</p>
</template>
  1. Setup the routes

.

const routes = [
  {
    path: "/",
    redirect: "/users"
  },
  {
    path: "/users",
    component: Users,
    children: [
      {
        path: ":id",
        component: User
      }
    ]
  }
];
  1. Run the application and call the root url (http://localhost:8080)
  2. You should get redirected to /users
  3. Click the button
  4. The url gets updated but the application won't navigate to the user view

How can I fix that? I would expect a rendered user view for http://localhost:8080/users/1

2 Answers

If you are defining the children route you have to declare <router-view></router-view> in the parent component.

Users.vue

<template>
  <div>
    Users Page
    <router-view></router-view>   // ---> define this
  </div>
</template>

User.vue

<template>
  <div>
    USER {{ $route.params.id }}
  </div>
</template>

Let me know if it helps.

I think you misunderstand the idea of nested route, when using the children path to a component, it will try to render the children in the <router-view> of that component. This would mean that It will try to render the User view in the <router-view> of Users components (not App.vue), but it not found any in Users so thats why nothing happens.

More information can be found here :https://router.vuejs.org/guide/essentials/nested-routes.html

In order to archive your goal

/users will render the users list

/users/:id will render the user profile

I think you can define the Users and User component differently Like this in routes.js :

const routes = [
  {
    path: '/',
    redirect: '/users'
  },
  {
    path: '/users',
    component: Users
  },
  {
    path: '/users/:id',
    component: User
  }
]
Related