Vue router nested routes renders with parent

Viewed 1910

So Iv'e tried to nest my routes unsuccessfully using Vue router.

{
    path: '/admin',
    name: 'Admin', component: () => import('pages/Admin'),
    children:[
      { path: 'stock', name: 'Stock', component: ()=> import('pages/Stock')},
    ]},

It did not work so I found out that I need to put inside the parent component. Now it works but if I load the page /admin/stock it renders the two componets. one on top of the others.

Why the parent component (/admin page) is still displayed?

Btw when I did the same thing without nesting the routes it worked perfectly fine and the components rendered seperatly(the snippet below).

{
    path: '/admin',
    name: 'Admin', component: () => import('pages/Admin'),
    children:[
     //no nested route
    ]},
  { path: 'admin/stock', name: 'Stock', component: ()=> import('../pages/Stock')},

Thanks for the help

1 Answers

You should include in "Admin" component a router-view tag. Admin component will work as a "layout" and it will render the children corresponding to the current route.

In example

Admin Component:

<template>
    <div>
        <div>
            Content present in all childrens
        </div>
        <router-view>
            <div>"Admin" page content</div>
        </router-view>
    </div>
</template>

Stock component:

<template>
    <div>
        "Stock" content
    </div>
</template>

When you go to /admin It will render:

    <div>
        <div>
            Content present in all childrens
        </div>
        <div>"Admin" page content</div>
    </div>

When you visit /admin/stock It will render:

    <div>
        <div>
            Content present in all childrens
        </div>
        <div>"Stock" content</div>
    </div>

Here you have a better example https://router.vuejs.org/guide/essentials/nested-routes.html

If you don't need reuse "Admin" component layout, you could use routes as you mentioned in the second case, without nesting them

Related