我正在尝试实现一种基于 firebase 的 firebase.auth().onAuthStateChanged()
检查用户登录状态的方法。我想在我的应用程序中使用它作为全局变量。
目前,我正在使用 Vue.observable
存储来设置我的登录状态的值。
store.js
export const store = Vue.observable({
signedIn: false,
});
export const mutations = {
setSignedIn(bool) {
store.signedIn = bool;
},
};
在我的应用程序启动时,我调用检查身份验证函数
App.vue
import {mutations} from './store'
this.$firebase.auth().onAuthStateChanged((user) => {
if (user) {
mutations.setSignedIn(true);
} else {
mutations.setSignedIn(false);
}
});
最后,在我的一个子组件中,我检查商店以查看登录状态。基于此,如果未登录,我将使用 chrome.storage
,如果已登录,我将使用 firebase
。
List.js
import {store} from './store'
if (store.signedIn) {
// use firebase
} else {
// use chrome storage
}
我的主要问题是 firebase.auth().onAuthStateChanged()
函数是异步
,因此我的 store.signedIn
值始终为false 并且更改时不会更新。
我的目标是等到onAuthStateChanged
完成并检查store.signedIn
,但到目前为止我的尝试尚未奏效。
最佳答案
创建一个名为 isSignedIn
的计算属性,然后使用 watch
选项监视它:
import {store} from './store'
export default{
...
computed:{
isSignedIn(){
return store.signedIn;
}
},
watch:{
isSignedIn(newVal,oldVal){
if (newVal) {
// use firebase
} else {
// use chrome storage
}
}
}
}
关于javascript - 观察 Vue Observable 中的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67976505/