Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue router 4 and vue 3 app showing component twice

I just installed vue-router 4 into a vue 3 application. When setting up my home route I keep getting the application displaying twice and even the navigation twice but cannot figure out why. I tried bringing in the Navigation component into App.vue and Home.vue but still shows twice. Is there something off that I am overlooking here?

router/index.js

import { createWebHistory, createRouter } from "vue-router";
import Home from "../components/Home";
import About from "@/components/About";

const routes = [
    {
        path: "/",
        name: "Home",
        component: Home,
    },
    {
        path: "/about",
        name: "About",
        component: About,
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;

Navigation.vue

<template>
  <div id="nav">
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
  </div>
  <router-view/>
</template>

<script>
export default {
  name: 'Navigation'
}
</script>

Home.vue

<template>
    <Header/>
    <Navigation/>
    <div>
        <About/>
    </div>
</template>

App.vue

<template>
  <Home/>
</template>

<script>
import Home from "@/components/Home";
export default {
  components: {Home}
}
</script>
like image 534
CodeConnoisseur Avatar asked Sep 01 '25 16:09

CodeConnoisseur


1 Answers

Home contains Navigation (which contains <router-view>, rendering the current route) and About. Since About is always rendered, you'd see two of them if the current route were /about.

<template>
  <Header/>
  <Navigation/> <!-- contains router-view -->
  <div>
    <About/> <!-- ❌ always rendered in addition to current route -->
  </div>
</template>

Your current route configuration has no child routes, so there should only be one <router-view>, and it's usually in the root component (App.vue):

App.vue:

<template>
  <Header />
  <Navigation />
  <router-view />
</template>

Navigation.vue:

<template>
  <div id="nav">
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
  </div>
  <!--<router-view/> ❌ move to App.vue -->
</template>

Home.vue:

<template>
  <!--<Header/> ​❌ move to App.vue -->
  <!--<Navigation/> ❌ move to App.vue -->
  <div>
    <About />
  </div>
</template>

demo

like image 176
tony19 Avatar answered Sep 04 '25 05:09

tony19