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

时间:2020-02-19 20:48:17

标签: vue.js vuejs2 vuex 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>

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

  methods: {
    async onLogin() {
      try{

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

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

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

    }
  }

我尝试通过计算属性获取状态,但是得到了相同的结果。我可以在Chrome Dev Tools的“应用程序”标签中看到vuex存储数据已更改,以指示我已正确登录/注销,但Vue Dev似乎一直在指示我已登录。。

注销时,我也遇到同样的问题。方法如下:

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

很高兴提供更多详细信息。

2 个答案:

答案 0 :(得分:4)

  1. store/index.js中添加以下内容:

     export const getters = {
       isAuthenticated(state) {
       return state.auth.loggedIn
      },
       loggedInUser(state) {
       return state.auth.user
      },
    };
    
  2. 在您认为已通过身份验证的页面中

    • 使用中间件auth作为middleware: 'auth'
    • 使用import { mapGetters } from 'vuex'
    • 在计算的加法...mapGetters(['isAuthenticated', 'loggedInUser']),
  3. 您可以使用loggingInUser来获取您的用户详细信息,或者检查是否经过isAuthenticated

,并且只要您在计算出的地图中导入地图获取器,注销操作就可以按预期进行

答案 1 :(得分:2)

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

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