【问题标题】:Vuex State returning values differentlyVuex State 返回值不同
【发布时间】:2021-02-28 12:37:46
【问题描述】:

我有一个系统,我在 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,
        });
      }

},

mutations.js

import defaultState from './state'

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

export default mutations

login.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 路由器操作的位置

router.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 有趣的是,当我控制台记录实际对象时,我确实得到了正确的值,请参阅下图以获得更多说明

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

【问题讨论】:

  • 您在设置用户之前重定向到仪表板。至于控制台行为,请查看this answer和this demo
  • 我从没想过从这个角度来看这是一个很好的收获@Dan 你能把它写成答案以便我标记它吗?

标签: javascript vue.js vuejs2 vuex vue-router


【解决方案1】:

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

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

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

这是一个说明性的demo 的实际操作。

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

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 2017-06-10
    • 2021-02-11
    • 2019-10-09
    • 2018-07-12
    • 1970-01-01
    • 2021-09-30
    • 2019-09-03
    • 2019-07-31
    相关资源
    最近更新 更多