acroscene
acroscene

Reputation: 1067

Set up router for subpages in Vue.js

I wounder how I best set up the router in Vue.js for handling ”subpages”. For example I got a navbar that routes to different pages. From one of these pages I want to have links to subpages. How do I best set this up?

I have done like this so far:

App.js

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view />
  </div>
</template>

Then I set up my router:

export default new Router({
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      path: "/about",
      name: "about",
      component: About,
      children: [
        {
          path: "/child1",
          name: "child1",
          component: Child1
        }
      ]
    }
  ]
})

And my About.vue where I provide the link to Child1

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <router-link to="/child1">Child1</router-link>
    <router-view></router-view>
  </div>
</template>

And finally my Child1.vue

<template>
  <div class="child1">
    <p>My message</p>
  </div>
</template>

My problem is that the link to Child1 is displayed both on the About page and on Child1 page. I just want to display it on the about page and only the content from the Child1 on the Child1 page

How is the best practice of setting up things like this?

Thanks

Upvotes: 1

Views: 2992

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

My problem is that the link to Child1 is displayed both on the About page and on Child1 page. I just want to display it on the about page

Just to clarify what's happening here: the link to Child1 is always visible within the About component even if child routes are active, but you don't want to show the link when the child route is active.

Way 1

You can provide fallback content to <router-view> when there is no matching route (i.e. when no child route is active). This would be a good opportunity to show the link.

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <router-view>
      <router-link to="/child1">Child1</router-link>
    </router-view>
  </div>
</template>

Way 2

The above solution may not work if your template is more complicated and if you want to situate the link elsewhere in the template.

So you'll have to manually control the visibility of the link by using v-if so that it is only visible when the child route is not active.

<template>
  <div class="about">
    <h1>This is an about page</h1>

    <!-- Show only when no child routes are active -->
    <router-link v-if="$route.name === 'about'" to="/child1">Child1</router-link>

    <!-- Or, do not show when Child1 route is active -->
    <router-link v-if="$route.name !== 'child1'" to="/child1">Child1</router-link>

    <router-view></router-view>
  </div>
</template>

Upvotes: 1

Related Questions