【问题标题】:Vue Replace Navbar With RouterVue用路由器替换导航栏
【发布时间】:2021-09-20 10:29:10
【问题描述】:

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

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

【问题讨论】:

  • 但是嵌套路由确实是正确的解决方案...
  • 我的意思是可能的解决方案之一。其他方法是仅在用户登录时有条件地显示导航栏部分......
  • 谢谢@MichalLevý,我明天需要再次尝试嵌套路由。关于用户登录后隐藏导航栏:我想在登录或注册页面隐藏导航栏。
  • 没关系 - 在这两种情况下用户都没有登录...

标签: vue.js vue-router vuejs3


【解决方案1】:

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

所以在创建了默认的 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 菜鸟,不确定以上是否是最好的方法,但它现在正在工作。

【讨论】:

    猜你喜欢
    • 2017-08-09
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2020-10-27
    • 2020-12-31
    • 2021-06-01
    • 2020-08-22
    • 2018-07-04
    相关资源
    最近更新 更多