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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With