vue-router: nested named views problem. Additional component is not visible

Viewed 1804

I found this example in vue-router documentation:

https://jsfiddle.net/posva/22wgksa3/?fbclid=IwAR2WITnr6cmA_3rUgOCCvPrHASKfSW9QsvEKv4HrxBmuDUN1VmWSWufCtAI

const router = new VueRouter({
   mode: 'history',
   routes: [{ 
       path: '/settings',
       // You could also have named views at tho top
       component: UserSettings,
       children: [{
           path: 'emails',
           component: UserEmailsSubscriptions
           }, {
           path: 'profile',
           components: {
               default: UserProfile,
               helper: UserProfilePreview
           }
       }]
   }]
})

I tried to do something like this:

https://jsfiddle.net/pt9o6h8e/

const router = new VueRouter({
   mode: 'history',
   routes: [{ 
       path: '/settings',
       components: {
           default: UserSettings,
           test: TestComponent
       }
       children: [{
           path: 'emails',
           component: UserEmailsSubscriptions
           }, {
           path: 'profile',
           components: {
               default: UserProfile,
               helper: UserProfilePreview
           }
       }]
   }]
})

but TestComponent is not visible. Why?

1 Answers

When you specified your route like this,

{ 
  path: '/settings',
  // You could also have named views at tho top
  components: {
    default: UserSettings,
    test: TestComponent
  }
}

UserSettings and TestComponent are considered sibling components so when rendering, it will look for a named router-view next to the default router-view that you specified on your top-most div which is #app.

However, you put <router-view name="test" /> inside UserSettings template so it didn't find the router-view to render TestComponent to.

To fix this, either move the test router-view from UserSettings to the #app.

<div id="app">
  <h1>Nested Named Views</h1>
  <router-view></router-view>
  <router-view name="test" class="us__content us__content--helper"/>
</div>

Or, if you want to keep it inside UserSettings, change how you declared it by moving test: TestComponent inside either of your children routes.

See working example.

Related