我有一个系统,我在 Vuex 中验证和存储用户数据,然后验证要显示或不显示哪些 View 。我有一个名为 LoggedIn 的属性,它只是一个 bool 值,用于检查用户是否登录。让我先向您展示 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
登录.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> 有趣的是,当我 console.log 实际对象时,我确实获得了正确的值,请参阅下图以获取更多说明
极其奇怪的行为不知道这样做的原因是什么,有人可以帮助我吗?
最佳答案
您在设置用户之前重定向到仪表板,这将在准备就绪之前触发 loggedIn
检查。
router.push({ name: "Dashboard" });
commit(SET_USER, response.data);
对于控制台行为,将对象或数组记录到控制台时,当您单击展开/查看属性时,控制台会显示单击时的属性,而不是日志的时间。这是可能的,因为 JavaScript 对象和数组是引用,因此控制台能够通过引用更新显示。
这是一个说明性的demo的行动。
(根据要求从我的评论转换而来。)
关于javascript - Vuex State 返回值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64872835/