首页 > 解决方案 > Vuex State 返回值不同

问题描述

我有一个系统,我在 Vuex 中验证和存储用户数据,然后验证要显示或不显示哪些视图。我有一个名为LoggedIn的属性,它只是一个用于检查用户是否登录的布尔值。让我先给你看一下 Vuex 的部分

Actions.js

async login({ commit }, loginData) {
    const email = loginData.user.email;
      try {
        commit(USER_REQUEST_START);
        const response = await apolloClient.mutate({
          mutation: loginAccount,
          variables: { email: email },
        });

        router.push({ name: "Dashboard" });

        commit(SET_USER, response.data);

        Vue.prototype.$snotify.success("Login Successfully", {
          showProgressBar: true,
          timeout: 2000,
        });
      } catch (error) {
        commit(USER_REQUEST_ERROR, error);
        Vue.prototype.$snotify.error(error.message || "Some thing went wrong", {
          showProgressBar: true,
          timeout: 2000,
        });
      }

},

突变.js

import defaultState from './state'

const mutations = {
  SET_USER(state, value) {
    state.data = value
    state.loggedIn = true
    state.loading = false
  },
}

export default mutations

登录.vue

async submitForm() {
      try {
        const data = await this.$firebase
          .auth()
          .signInWithEmailAndPassword(this.email, this.password)
        const idTokenResult = await data.user
          .getIdTokenResult()
          .then((data) => data)

        const authTime = idTokenResult.claims.auth_time * 1000
        const sessionDuration = this.getSessionDuraion(
          authTime,
          SESSION_EXPIRE_DAYS,
        )
        const millisecondsUntilExpiration =
          new Date(sessionDuration).getTime() - authTime
        this.$store.dispatch('setUserSession', sessionDuration)
        setTimeout(() => {
          this.$firebase.auth().signOut()
        }, millisecondsUntilExpiration)
        this.$store.dispatch('login', data)
      } catch (error) {
        this.$snotify.error(
          (error && error.message) || 'Some thing went wrong',
          {
            showProgressBar: true,
            timeout: 2000,
          },
        )
      }
    },

此登录方法验证用户在 Vuex 中设置用户状态,并应重定向到仪表板(这是问题所在)调用以下 vuejs 路由器操作

路由器.js

router.beforeEach((to, from, next) => {
  const isAuthenticated = store.state.user.loggedIn
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
  console.log(store.state.user);
  console.log(store.state.user.loggedIn);
  if (requiresAuth && !isAuthenticated) {
    next({name: 'Login'})
  } else {
    if (store.state.user.sessionTimeOut && !store.getters.isSessionValid) {
      sessionMixin.methods.clearSessionStorage()
      next({name: 'Login'})
    } else {
      next(true)
    }
  }
})

这是我遇到问题的地方,router.beforeEach仅用于在未经身份验证的情况下注销和其他进程。现在,当我登录用户设置状态时,虽然没有错误,但是一个非常奇怪的问题,条件isAuthenticated不起作用,当我尝试控制台记录它时它返回false有趣的部分是当我 console.log 实际对象我确实得到正确的值,请参阅下图以获得更多说明在此处输入图像描述

非常奇怪的行为不知道这样做的原因是什么,有人可以帮助我吗?

标签: javascriptvue.jsvuejs2vuexvue-router

解决方案


您在设置用户之前重定向到仪表板,这将loggedIn在准备好之前触发检查。

router.push({ name: "Dashboard" });
commit(SET_USER, response.data);

至于控制台行为,当将对象或数组记录到控制台时,当您单击展开/查看属性时,控制台会显示单击时的属性,而不是日志时属性。这是可能的,因为 JavaScript 对象和数组是引用,因此控制台能够通过引用更新显示。

这是一个说明性的演示

(根据要求从我的评论转换。)


推荐阅读