【问题标题】:Vue.js show and hide the navbar on different pages of the routingVue.js 在路由的不同页面上显示和隐藏导航栏
【发布时间】:2022-10-14 02:40:56
【问题描述】:

这是我的 App.vue 模板。我想在localStorage 中名为'auth' 的变量为真时显示<Sidebar>,因为如果'auth' 为假,我在Login 页面,不需要Sidebar。我已经在computed: 部分声明了函数checkAuthStatus

App.vue

<template>
  <div class="page">
    <div v-show="checkAuthStatus" class="logobar">
      <p>This is the logobar</p>
    </div>
    <div class="sidebar_content">
      <Sidebar v-show="checkAuthStatus" />
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    checkAuthStatus() {
      if (localStorage.getItem('auth') === 'true') return true
      else return false
    },
  },
}
</script>

Login.vue

在登录页面中,我有一个登录按钮,其中包含以下@click.prevent 功能。

<template>
  <form action="">
    <div class="field">
      <lable class="font-color-blue">E-mail</lable>
      <input type="email" placeholder="Email" />
    </div>
    <br />
    <div class="field">
      <lable class="font-color-blue">Password</lable>
      <input type="password" class="form-control" placeholder="Password" />
    </div>
    <br />
    <div class="center">
      <button id="login" class="button" @click.prevent="login">Login</button>
    </div>
  </form>
</template>

<script>
export default {
  methods: {
    login() {
      localStorage.setItem('auth', 'true')
      this.$router.push('/orders')
    },
  },
}
</script>

它把我带到了'/orders/' 链接,但在我手动刷新页面之前,侧边栏不会显示。我试过this.$router.go('/orders');this.$nextTick(() =&gt; this.$router.push('/orders'));。我也试过v-showv-if,但没有任何效果。你有什么建议吗?

【问题讨论】:

  • checkAuthStatus的代码是什么?你在那里有正确的依赖关系吗?
  • 它只是一个 if 语句,根据 localStorage 中 'auth' 变量的值返回 true 或 false。它可以正常工作,因为在我刷新页面后会显示侧边栏。
  • 无论如何,您都不应该刷新页面,因此无论如何您都可以忘记那个“解决方案”。你在你的 Vue 开发工具中看到了什么计算状态?合适的值?你能用所有相关代码编辑你的sn-p吗?或者向我们提供minimal reproducible example
  • 您需要侧边栏中的一些代码吗?
  • 海事组织应该没问题。您在 Vue 开发工具中看到了什么?正确的状态+本地存储?

标签: routes vuejs3 navbar


【解决方案1】:

我在登录页面中使用$emit 解决了这个问题,该页面绑定到 App.vue 中的login() 方法

App.vue

<template>
  <div class="page">
    <div v-show="isLoggedIn" class="logobar">
      <p>This is the logobar</p>
    </div>
    <div class="sidebar_content">
      <Sidebar v-show="isLoggedIn" />
      <router-view @login="login"></router-view>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    isLoggedIn: false
  }
  methods: {
    login() {
      this.isLoggedIn= true;
      localStorage.setItem('auth', 'true');
    },
  },
}
</script>

【讨论】:

    猜你喜欢
    • 2012-08-24
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    相关资源
    最近更新 更多