0

I'm trying to set up a routing system with vue. For my purpose, I need a fixed navbar on the top that needs to be displayed on every page and a sidebar that I want to display only on the settings page. Following the documentation I tried:

const routes = [
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    children: [
      {
        path: 'route1',
        name: 'Route1',
        component: Route1
      },
      {
        path: 'route2',
        name: 'Route2',
        component: Route2
      }
    ]
  }
]

Then on the settings template:

<template>
  <div class="flex items-start">
    <div class="lg:w-3/12 w-12 sm:w-16 md:w-24 pb-10 lg:pr-8">
      <Sidebar />
    </div>
  </div>
  <div class="lg:w-9/12 w-full pt-10 pb-8 text-justify">
  // My subroute goes here  
  </div>
</template>

I feel that I'm missing something. First, I can't understand how to properly display the subroutes. I tried with <router-view /> but it seems to refer to the parent navigation. Second, I don't want the user to visit the /settings route but only /settings/route1 and settings/route2.

I can achieve this by simply adding the sidebar in every settings route but this seems bad because it forces the <Sidebar/> component to be mounted every time

Where am I wrong? Thanks

1
  • Hi, as you are using the nested routes, then it will always refer to the parent navigation, and to display the nested route you need to use <router-view></router-view>. Commented Mar 21, 2021 at 17:07

1 Answer 1

2

As you probably have guessed, the <router-view /> element goes in your Settings component:

<template>
  <div class="flex items-start">
    <div class="lg:w-3/12 w-12 sm:w-16 md:w-24 pb-10 lg:pr-8">
      <Sidebar />
    </div>
  </div>
  <div class="lg:w-9/12 w-full pt-10 pb-8 text-justify">
    <router-view /> <!-- Here is your router view --> 
  </div>
</template>

Then as it was pointed out in the comments, /settings will always be a valid route. What you can do when the client directly navigates to /settings is to replace the current route with one of the two children (possibly based on some logic) in the mounted hook:

  mounted() {
    if(this.$router.currentRoute.path.endsWith('/settings')) {
      this.$router.replace('/settings/route1')
    }
  }

Or use $router.push() instead based on what you want the navigation history to look like.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.