Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide global component (e.g navbar) on some routes?

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?

like image 665
dan martin Avatar asked Oct 29 '19 21:10

dan martin


2 Answers

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" />
like image 55
AlbinR Avatar answered Oct 12 '22 01:10

AlbinR


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
  },
},
like image 22
TommyF Avatar answered Oct 12 '22 02:10

TommyF