So the vast majority of views on my vuejs SPA have a navbar component at the top. However, some select views such as the login should not display this.
My workaround was to import the navbar and add to each view individually if it was needed, but now I can see it causes a weird flickering when going from one view to another - presumably because the navbar component is being removed, and immediately re-added. This seems wrong.
I assume there's some way to add the navbar component in App.vue but conditionally hide it on some routes with vue-router? What's the best practice for this?
Route Meta Fields solved this problem for me:
//router.js
{
path: '/login',
name: 'login',
component: () => import(/* webpackChunkName: 'login' */ '@/components/Login.vue'),
meta: {
hideNavbar: true,
}
}
//App.vue
<Navbar v-if="!$route.meta.hideNavbar" />
I prefer a conditionally rendered component in the main view over @Edins nested routes approach.
Vue provides a great global state store via Vuex
which makes this incredibly simple as well.
The classic example would be to only have the navbar when the user is logged in.
So you track the login status in the state store, then use a computed getter in your main view (or App.vue):
<template>
<navbar v-if="isAuthenticated"/>
<router-view/>
</template>
export default {
name: 'App',
computed: {
isAuthenticated() {
return this.$store.getters.isAuthenticated
},
},
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