vue.jsvuejs2

Vue.js nested routing with default child


I have an issue with a default child route in Vue.js 2.

When I visit localhost/listings initially, it correctly loads index.vue and map.vue as a child.

When I navigate using router-link to localhost/listings/1, and then using router-link back to localhost/listings, then it still loads the show.vue template. This shouldn't happen?

I have no navigation guards or anything that should interfere. Is there anyway to correct this?

My routes:

window.router = new VueRouter({
  routes: [
    ...

    {
      path: '/listings',
      name: 'listing.index',
      component: require('./components/listing/index.vue'),
      children: [
        {
          path: '',
          component: require('./components/listing/map.vue')
        },
        {
          path: ':id',
          name: 'listing.show',
          component: require('./components/listing/show.vue')
        }
      ]
    },
    
    ...
  ]
});

Solution

  • Maybe try re-arranging the children, routes are fired in the order they match from top-to-bottom, so this should hopefully fix it:

    window.router = new VueRouter({
        routes: [
    
        ...
    
        {
            path: '/listings',
            name: 'listing.index',
            component: require('./components/listing/index.vue'),
            children: [
                {
                    path: ':id',
                    name: 'listing.show',
                    component: require('./components/listing/show.vue')
                }
                {
                    path: '',
                    component: require('./components/listing/map.vue')
                },
            ]
        },
    
        ...
    
      ]
    });
    

    Just for a bit of clarification, your path: '' essentially serves as a "catch all", which is likely why when it's at the top it's being found immediately and so the router never propagates any further down to the :id route.