我的应用程序使用 Firebase API 进行用户身份验证,将登录状态保存为 Vuex 状态中的布尔值。
当用户登录时,我会设置登录状态,并相应地有条件地显示登录/注销按钮。
但当页面刷新时,vue 应用程序的状态将丢失并重置为默认状态
这就造成了一个问题,即使用户已登录并刷新页面,登录状态也会被设置为false,并且即使用户保持登录状态,显示的也是登录按钮而不是注销按钮....。
我该如何防止这种行为?
我是否应该使用 cookie 或其他更好的解决方案...
这是一个已知的使用案例。有不同的解决方案。
例如,可以使用 vuex-persistedstate
。这是 vuex
的一个插件,用于在页面刷新之间处理和存储状态。
示例代码:
导入 { 存储 }从 'vuex';
import createPersistedState from 'vuex-persistedstate';
import * as Cookies from 'js-cookie';
const store = new Store({
// ...
插件[
createPersistedState({
getState: (key) => Cookies.getJSON(key)、
setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true })
})
]
})
我们要做的很简单:
js-cookie
getState
中,我们尝试从 Cookies
中加载已保存的状态setState
中,我们将状态保存到 Cookies
中我认为使用 cookies/localStorage 保存登录状态可能会在某些情况下导致错误; Firebase 已经在本地存储中为我们记录了登录信息,包括过期时间和刷新令牌; 因此,我将使用 Vue 创建的钩子和 Firebase api 来检查登录状态; 如果令牌过期,api 将为我们刷新令牌; 因此,我们可以确保应用程序中显示的登录状态与 Firebase 相同。
new Vue({
el: '#app',
created() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
log('User is logined');
// update data or vuex state
} else {
log('User is not logged in.');
}
});
},
});
每次重新加载并获取用户数据时,我都会重置标头,从而解决了这个问题,但我不知道哪种方法更好......
new Vue({
el: 'vue',
render: h => h(VueBox),
router,
store,
computed: {
tokenJWT () {
return this.$store.getters.tokenCheck
},
},
created() {
this.setAuth()
},
methods:
Object.assign({}, mapActions(['setUser']), {
setAuth(){
if (this.tokenJWT) {
if (this.tokenJWT === 'expired') {
this.$store.dispatch('destroyAuth')
this.$store.dispatch('openModal')
this.$store.dispatch('setElModal', 'form-login')
} else {
window.axios.defaults.headers.common = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + this.tokenJWT
}
axios.get( api.domain + api.authApi )
.then(res => {
if (res.status == 200) {
this.setUser( res.data.user )
}
})
.catch( errors => {
console.log(errors)
this.destroyAuth()
})
}
}
}
})
})