繁体   English   中英

使用 nuxt auth 模块检测身份验证状态需要刷新

[英]Refresh required to detect authentication state using nuxt auth module

我的应用程序无法检测用户在未完全刷新页面的情况下登录时发生的状态更改。 刷新后一切正常显示。 我正在使用 Nuxt 及其包含的身份验证模块,这里记录了 - https://auth.nuxtjs.org/

这是无法检测状态变化的 v-if 语句:

  <template v-if="$auth.$state.loggedIn">
    <nuxt-link
      to="/profile"
    >
      Hello, {{ $auth.$state.user.name }}
    </nuxt-link>
  </template>
  <template v-else>
    <nuxt-link
      to="/logIn"
    >
      Sign In
    </nuxt-link>
  </template>

这是我的登录页面中的登录方法。

  methods: {
    async onLogin() {
      try{

        this.$auth.loginWith("local", {
          data: {
            email: this.email,
            password: this.password
          }
        });

        this.$router.push("/");

      }catch(err){
        console.log(err);
      }

    }
  }

我尝试通过计算属性获取状态,但得到了相同的结果。 我可以看到 vuex 存储数据发生变化,表明我在 Chrome Dev Tools 的“应用程序”选项卡中正确登录/注销,但 Vue Dev 似乎不断表明我已登录......但不确定它是否只是错误。 .

注销时我也遇到了同样的问题。 这是方法:

async onLogout() {
  try{
    await this.$auth.logout();
  }catch(err){
    console.log(err);
  }
}

我很高兴提供更多细节。

  1. store/index.js添加这个:

     export const getters = { isAuthenticated(state) { return state.auth.loggedIn }, loggedInUser(state) { return state.auth.user }, };
  2. 在您应该进行身份验证的页面中

    • 使用中间件身份验证为: middleware: 'auth'
    • 使用import { mapGetters } from 'vuex'
    • 在计算中添加...mapGetters(['isAuthenticated', 'loggedInUser']),
  3. 您可以使用 loginUser 获取您的用户详细信息或检查 isAuthenticated

并且只要您在计算中导入地图获取器,注销就会按预期工作

有时 Vue 的反应性系统不足,您只需要手动触发重新渲染,最简单的方法是将函数逻辑包装在setTimeout()

setTimeout(async () => {
   await this.$auth.logout();
}, 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM