在 Vue Observable 中观察变化

Watch Changes in Vue Observable

我正在尝试实现一种基于 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() 函数是 asynchronous 因此我的 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
      }
 }
}
}