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

new*_*mer 6 vue.js vuex vuejs2 nuxt.js

我的应用程序无法检测用户在未完全刷新页面的情况下登录时发生的状态更改。刷新后一切正常显示。我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

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

  methods: {
    async onLogin() {
      try{

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

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

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

    }
  }
Run Code Online (Sandbox Code Playgroud)

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

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

async onLogout() {
  try{
    await this.$auth.logout();
  }catch(err){
    console.log(err);
  }
}
Run Code Online (Sandbox Code Playgroud)

我很高兴提供更多细节。

M.a*_*man 8

  1. store/index.js补充一点:

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

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

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

  • 这并不能解决以下问题:如果您清除 cookie 和 localstorage,然后在 SPA 下的应用程序中再单击几个页面,它不会再次检查身份验证,因此注销的用户仍在访问他们不应该访问的页面。 (2认同)