问题描述
我的应用使用 Firebase API 进行用户身份验证,将登录状态保存为 Vuex 状态中的布尔值.
My app uses the Firebase API for User Authentication, saving the Login status as a boolean value in a Vuex State.
当用户登录时,我会设置登录状态并相应地有条件地显示登录/注销按钮.
When the user logs in I set the login status and conditionally display the Login/Logout button accordingly.
但是当页面刷新时,vue app的状态丢失并重置为默认
But when the page is refreshed, the state of the vue app is lost and reset to default
这会导致一个问题,即使当用户登录并刷新页面时,登录状态 也会设置回 false 并且显示登录按钮而不是即使用户保持登录状态,注销按钮....
This causes a problem as even when the user is logged in and the page is refreshed the login status is set back to false and the login button is displayed instead of logout button even though the user stays logged in....
我该怎么做才能防止这种行为
我可以使用 cookies或者任何其他更好的解决方案可用...
Shall I use cookiesOr any other better solution is available...
- ——
推荐答案
这是一个已知用例.有不同的解决方案.
This is a known use case. There are different solutions.
例如,可以使用 vuex-persistedstate
.这是 vuex
的插件,用于处理和存储页面刷新之间的状态.
For example, one can use vuex-persistedstate
. This is a plugin for vuex
to handle and store state between page refreshes.
示例代码:
import { Store } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
const store = new Store({
// ...
plugins: [
createPersistedState({
getState: (key) => Cookies.getJSON(key),
setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true })
})
]
})
我们在这里做的很简单:
What we do here is simple:
- 您需要安装
js-cookie
- 在
getState
上,我们尝试从Cookies
加载保存的状态 - 在
setState
上,我们将状态保存到Cookies
- you need to install
js-cookie
- on
getState
we try to load saved state fromCookies
- on
setState
we save our state toCookies
文档和安装说明:https://www.npmjs.com/package/vuex-persistedstate
这篇关于页面刷新时的 Vuex 状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!