【问题标题】:Watch Changes in Vue Observable观察 Vue Observable 的变化
【发布时间】:2021-08-30 17:29:43
【问题描述】:

我正在尝试实现一种基于 firebase 的firebase.auth().onAuthStateChanged() 检查用户登录状态的方法。我想在我的应用程序中使用它作为全局变量。

目前,我正在使用Vue.observable 存储来设置我的登录状态的值。

store.js

export const store = Vue.observable({
  signedIn: false,
});

export const mutations = {
  setSignedIn(bool) {
    store.signedIn = bool;
  },
};

在我的应用程序开始时,我调用了 check auth 函数 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,但到目前为止我的尝试还没有奏效。

【问题讨论】:

  • 你在哪里运行this.$firebase.auth().onAuthStateChanged...

标签: javascript firebase vue.js google-chrome-extension firebase-authentication


【解决方案1】:

创建一个名为 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
      }
 }
}
}

【讨论】:

    猜你喜欢
    • 2013-08-13
    • 2021-01-12
    • 2019-12-18
    • 2019-09-11
    • 2021-04-22
    • 1970-01-01
    • 2020-03-26
    • 2017-12-28
    • 2012-08-05
    相关资源
    最近更新 更多