首页 > 解决方案 > Meteor.userId() 在浏览器刷新时丢失

问题描述

我使用 Meteor.userId() 来检查用户是否已登录。这在用户未登录(Meteor.userId() 为空)和用户已登录(Meteor.userId() 不为空)时效果很好,但是如果用户已登录并且浏览器已刷新 Meteor。 userId() 丢失。

有哪些社区建议来跟踪用户是否已登录?如果用户已经登录并且浏览器被刷新,我应该将用户重定向到登录页面吗?用户登录后,我是否应该将 Meteor.userId() 保存在本地存储中(我认为它不会起作用)?

更新 1:Meteor.userId() MainNavBar 根据对App.vue 的方法调用显示用户是否登录。

MainNavBar.vue

<li class="nav-item d-xl-block" v-if="(this.$root.currentUserId==null)">
            <router-link class="nav-link" v-bind:to="{ name: 'register' }">Register</router-link>
          </li>
          <li class="nav-item d-xl-block" v-else>
            <a class="nav-link" href='' data-cy="logout" v-on:click="Logout()">Log out</a>
          </li>

应用程序.vue:

<script>
import { mapGetters } from 'vuex';
import { Meteor } from 'meteor/meteor';
export default 
{
  computed: {
    ...mapGetters('layout', ['showCart',]),
  },
  meteor: 
  {
    currentUserId()
    {
      return Meteor.userId();
    },
  },
}
</script>

更新 1: 根据评论,我需要使用 全局导航守卫 ,这将使路由器等待用户订阅准备好。

如果 Meteor.userId() 不存在,我有以下代码将用户重定向到登录页面。如何使用 Meteor.loggingIn()更改代码以使“路由器等待用户订阅准备就绪” 。Meteor.loggingIn() 是一个反应式数据源。

router.beforeEach((to, from, next) => 
  {
    //I need to wait here till Meteor.loggingIn() returns true? 
    let loggingIn= Meteor.loggingIn();
    if (loggingIn && Meteor.userId() == null && 
      to.name ==='dashboard'
    {
      next('/login');
    }
    else 
    {
      next();
    }
  });

标签: javascriptvue.jsmeteormeteor-accounts

解决方案


推荐阅读