javascript - 观察 Vue Observable 中的变化

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

我正在尝试实现一种基于 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/

相关文章:

javascript - jQuery 插件不能在 .vue 组件中工作

javascript - 如何在 Vue 中选择所有具有特定关键字的 $refs?

javascript - 如何将自定义 javascript 添加到谷歌网站?

ios - 没有 Cocoapods - 需要手动为 iOS 添加性能监控

javascript - 如何将键/值对添加到 JavaScript 对象?

swift - 显示登录用户特有的收藏夹

android - 使用 Firebase 将图像检索到 RecyclerView 时无法创建 Firebase 存储网络请求 android.os.RemoteException

vue.js - 如何使多个搜索过滤器与 Vue Bootstrap 中的 for 循环一起使用?

javascript - 防止 MVC 中的多次提交

javascript - 单击按钮时 HTML 函数不返回值