Vue 用路由器替换导航栏

时间:2021-07-10 11:35:34

标签: vue.js vue-router vuejs3

Vue 新手在这里。使用 Vue-CLI 创建的开箱即用的默认应用程序,包括 Vue Router,顶部导航栏带有主页和关于链接。我想要的是:当您点击“关于”链接时,它不会更新导航栏下方的内容,而是更新整个页面,即使导航栏消失。

enter image description here

在 App.vue 中:

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

路由器在 router/index.js 中设置为:

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;

这是为了模拟一个通常没有导航栏的典型登录页面。

我玩过嵌套路由器但没有运气。我使用的是 Vue 3。

1 个答案:

答案 0 :(得分:0)

我通过将导航链接提取到它自己的组件中解决了这个问题,并且只在需要它的页面上显示导航链接。这意味着在注册页面中我不包含导航链接。

所以在创建默认的 Vue-CLI 启动应用程序后,我删除了导航组件:

<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>

并创建了一个新的 Nav.vue 组件:

<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>

将导航组件添加到我希望导航显示的页面,例如主页.vue:

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

我的登录中没有包含导航:

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

作为一个 Vue 菜鸟,不确定上面的方法是否是最好的方法,但它现在有效。