Using the code below, the component SiteHead will appear on ALL pages, at the very top, above all other components but I only want this to happen for the HomeView.vue page.
I would like the component to be at the very top of the HomeView page, above the SiteNavigation component. Placing the SiteHead component into the HomeView.vue code would place this below SiteNavigation.
How would I go about this?
This is my App.vue code:
<template>
<div >
<SiteHead />
<SiteNavigation />
<RouterView />
<SiteFooter />
</div>
</template>
<script setup>
import {RouterView} from "vue-router";
import SiteNavigation from "./components/SiteNavigation.vue";
import SiteFooter from "./components/SiteFooter.vue";
import SiteHead from "./components/SiteHead.vue";
</script>
<style lang="scss" scoped>
</style>
and this is my HomeView.vue code (pretty much empty at the moment though):
<script setup>
</script>
<template>
<main>
<p >Home</p>
</main>
</template>
CodePudding user response:
You could achieve this is by placing the SiteHead
component inside the template of the HomeView.vue
file, and not in the App.vue
file.
HomeView.vue file:
<template>
<main>
<SiteHead />
<p >Home</p>
</main>
</template>
<script setup>
import SiteHead from "./components/SiteHead.vue";
export default {
components: {
SiteHead
}
}
</script>
Solution 2
Alternatively you can conditionally render the SiteHead
component in the App.vue
template, using the v-if
directive. To do this, you need to use a computed property to determine if the current route is the home page. So here is how your App.vue
should look like:
<template>
<div >
<SiteHead v-if="isHomePage" />
<SiteNavigation />
<RouterView />
<SiteFooter />
</div>
</template>
<script setup>
import { computed } from 'vue'
import {RouterView, useRoute} from "vue-router";
import SiteNavigation from "./components/SiteNavigation.vue";
import SiteFooter from "./components/SiteFooter.vue";
import SiteHead from "./components/SiteHead.vue";
const Route = useRoute();
const isHomePage= computed(() => {
return Route.path === '/'
})
</script>
CodePudding user response:
You could make use of the teleport
feature of Vue3:
Documentation: https://vuejs.org/guide/built-ins/teleport.html#basic-usage
App.vue
:
<template>
<div >
<div id="site-head"></div>
<SiteNavigation />
<RouterView />
<SiteFooter />
</div>
</template>
<script setup>
import {RouterView} from "vue-router";
import SiteNavigation from "./components/SiteNavigation.vue";
import SiteFooter from "./components/SiteFooter.vue";
</script>
<style lang="scss" scoped>
</style>
HomeView.vue
<template>
<main>
<p >Home</p>
<Teleport to="#site-head">
<SiteHead />
</Teleport>
</main>
</template>
<script setup>
import SiteHead from "./components/SiteHead.vue";
</script>