Ruslan Bairamovi
Ruslan Bairamovi

Reputation: 458

Vue, how can I render different navbar due to route?

I am new at Vue.js. I am working on demo project. In my project, I have three different navbar. First one for HomePage, second one for Login/Register page and third one is for Dashboard. In frameworks like React and Vue we set one global navbar for all pages. How can I render this three navbar components conditionally ? What is the best practice for that ? I want to set vuex for solve that, is that a right approach ?

Upvotes: 0

Views: 1014

Answers (2)

Prakhar Gupta
Prakhar Gupta

Reputation: 101

Actually what you can do is make a navbar component and use v-if to check on which route you are currently on. You can use the $route object to verify the current URL and use computed to check if the route name or params/queries are the same as you want.

computed: {
  dashboard() {
     return this.$route.name === 'Dashboard'
  }
}

And then in your navbar component use v-if="dashboard" to check your conditions

Upvotes: 1

catmal
catmal

Reputation: 1758

You can do it using named routes. In your component you set multiple named router views:

  <router-view name="navbar"></router-view>
  <router-view ></router-view>

And in routes you set which component to render and where:

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: HomeContent,
        navbar: HomeNavbar,
      }
    },
    {
      path: '/dashboard',
      components: {
        default: DashboardContent,
        navbar: DashboardNavbar,
      }
    }
  ]
})

Otherwise you can set a conditional in the component and render navbar based on route:

  if ($route.path === home) {
   <NavbarHome />
  }

If navbars have much in common you can just use a conditional for elements that are in one but not in another.

Upvotes: 3

Related Questions