Home > other >  Additional nested <router-view /> does not render view from child route
Additional nested <router-view /> does not render view from child route

Time:10-19

I setup a new Vue3 project with routing. Inside src I create a new directory "foo" with a Index.vue

    <template>
      <div>
        <div>Foo</div>
        <router-view />
      </div>
    </template>

and a subdirectory "views" with a Home.vue

    <template>
      <div>Bar</div>
    </template>

Inside the foo directory I also setup a router.js where I register all the views for that feature

    import Index from "./Index.vue";
    import Home from "./views/Home.vue";
    
    const featureRoute = {
      path: "/foo",
      component: Index,
      children: [
        {
          path: "/",
          component: Home,
        },
      ],
    };
    
    export default router => {
      router.addRoute(featureRoute);
    };

Inside the main router file I change the code to

    import { createRouter, createWebHistory } from "vue-router";
    
    import registerFooRouter from "../foo/router";
    
    const routes = [
      {
        path: "/",
        redirect: "/foo",
      },
    ];
    
    const router = createRouter({
      history: createWebHistory(process.env.BASE_URL),
      routes,
    });
    
    registerFooRouter(router);
    
    export default router;

The App.vue:

    <template>
      <router-view />
    </template>

What I expect:

When running the app I get redirected to /foo. It will render a div with the content "Foo" and below that is another div with the content "Bar"

What happens:

The redirection works fine. But unfortunately all I see is the div with the content "Foo". The second div with the content "Bar" is missing.


So it seems it is not able to render the Home.vue file.

Does someone know what's missing here?

CodePudding user response:

path: "/", inside children is interpreted as root path by Vue Router. If you want to render something "default" inside the "/foo" route, use empty string:

const featureRoute = {
  path: "/foo",
  component: Index,
  children: [
    {
      path: "",
      component: Home,
    },
  ],
};

Check last example in the docs

  • Related