'Vue Router duplicate header
I'm working on a vue3 project.
The idea is to have a main component composed by a header and 2 view.
When someone click on the h1 button I want to show the relative content under the header but vue-router keep duplicating the entire main component instead of only append the h1 components content under the header
/* main.ts */
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import main from './components/main.vue'
import h1 from './components/h1.vue'
import h2 from './components/h2.vue'
const routes = [
{
path: '/',
component: main,
children: [
{ path: 'h1', component: h1 },
{ path: 'h2', component: h2 },
],
},
]
const router = createRouter({
history: createWebHistory(),
routes,
})
createApp(App).use(router).mount('#app')
<template>
<!-- main.vue -->
<div style="display:flex; flex-direction:column">
<header>Header
<router-link to="h1" >h1</router-link>
<router-link to="h2" >h2</router-link>
</header>
<!-- Here ↓↓↓ I should see only the content from h1 -->
<router-view />
</div>
</template>
<template>
<!-- h1.vue -->
<!-- h2 is the same with: Hi I'm H2 -->
<div>
Hi I'm H1
</div>
</template>
I hope that everything is clear.
To replicate the environment
yarn create vite or npx create vite
choose a vue 3 template then add vue-router as dependency.
Solution 1:[1]
So, I've found that for what I need to do vue-router give you the option of using router-view and the component(s) option in route configuration to setup the layout.
Check out named view @ router-vue docs for further info.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ttyago |
