Vue Replace Navbar With Router

Viewed 617

Vue newbie here. With the out-of-box default app created by Vue-CLI, including Vue Router, you have the top navbar with the Home and About links. What I want is: when you click on the About link, instead of updating the content below the navbar, it will update the entire page i.e. making the navbar disappear.

enter image description here

In App.vue:

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

The router is set-up in router/index.js as:

import { createRouter, createWebHashHistory } from "vue-router";
import Home from "../views/Home.vue";

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/about",
    name: "About",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

export default router;

This is to simulate a typical login page where you often don't get navbar.

I played with nested routers but no luck. I'm using Vue 3.

1 Answers

I solved this by extracting the nav links into its own component, and only display the nav links on the pages that need it. This means in the sign-up page I do not include the nav links.

So after creating the default Vue-CLI starting app, I removed the nav components:

<template>
  <!-- <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link> |
    <router-link to="/signin">Sign In</router-link>
  </div> -->
  <router-view />
</template>

And created a new Nav.vue component:

<template>
  <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link> |
    <router-link to="/signin">Sign In</router-link>
  </div>
</template>

Added the Nav component to the pages where I want the nav to show, e.g. Home.vue:

<template>
  <Nav />
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>

I do not include the nav in my sign-in:

<template>This is the SIGN IN page - note there is no navigation links.</template>

Being a Vue noob, not sure if the above is the best approach, but it is working for now.

Related