Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to nest routing in Vue with many children?

I have three main views that each holds its own mark-up and unique content. The plan was to handle it like this: overview over the views

View 1: Users

List all users, links to each user, which is view 2. With a routerlink you go to view2.

<router-link v-bind:to="'/user/' + user.id">

View 2: Albums List all albums for the user. Link to press to see each album which takes you to view 3. I grab the id from url with

data() {
    return {
      id: this.$route.params.id,

this works fine, I then use the id to fetch data from an API. The problem starts now when I want to nest a new layer down to view 3 (photoView). Here I have a problem with nesting: If possible I want to use a url like

"/user/:id/albums/:id"

I have tried to set the routes to the this:

{ path: "/user/:id/albums/:id", component: PhotoView },

And the router.link in view2 (albumview) to:

<router-link v-bind:to="'/user/' + id + '/album/' + album.id">
                  <p>{{ album.title }}</p>
                </router-link>

This doesn´t work. I then tried to put the path to photoView as a child to the albumview, and this works.

{
    path: "/user/:id",
    component: AlbumView,
    ///
     children: [{ path: "/user/album:id", component: PhotoView }],
  },

BUT PROBLEM now. I render both views, the photoview just stack up under the albumview… as I in the albumview has the <router-view></router-view>

So I tried to put them in a container (and routerview in the container), like this: Routing: { path: "/user/", component: Container, /// children: [ { path: "/user/:id", component: AlbumView }, { path: "/user/album:id", component: PhotoView }, ], }, } new routing set-up, with multiple children

This doesn’t work, only the albumview shows. When I click on each album, it's just set the url as expected but routing won't work. What do I do wrong? What's the best solution to fix this?

I grab the id in both views like this
 data() {
    return {
      id: this.$route.params.id,
like image 214
bjorn Avatar asked Nov 21 '25 20:11

bjorn


1 Answers

When routing to a component with route params, a property is created on the $route.params object for each matched param.

So if there are multiple params in the route definition with the same name: id, only the last one will be stored in the $route.params.id property, the others will be overwritten and lost.

Give the params different names in the route definition:

{
  path: "/user/:idUser/albums/:idAlbum",
  component: PhotoView
},

Access these in the component as:

  • this.$route.params.idUser
  • this.$route.params.idAlbum
like image 93
Dan Avatar answered Nov 24 '25 10:11

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!