如何在vue js项目中检测用户的firebase身份验证登录状态?

Posted

技术标签:

【中文标题】如何在vue js项目中检测用户的firebase身份验证登录状态?【英文标题】:How to detect the user's firebase authentication login status in a vue js project? 【发布时间】:2020-12-23 18:26:21 【问题描述】:

我正在尝试检测用户状态。如果用户已登录,我想将数据“userstate”设置为 true。我在我的 vue 项目中使用 vuefire 和 firebase。试了下图的方法,还是不行

 data() 
    return 
        userstate:false
    ;
  ,


watch:
    userstate:
    firebase.auth().onAuthStateChanged(function(user)
        if(user)
        this.userstate= true;
        else
        this.userstate=false;
        
        )

【问题讨论】:

【参考方案1】:

在 Firebase 中,您可以使用 firebase 提供的 auth().currentUser

函数来检查用户是否已登录
// user will return true which means user EXISTS!
let user = firebase.auth().currentUser; 

if (user)   
  this.userstate = true; // If it exists
 else  
 this.userstate = false; // If it doesn't
 

在某些情况下,上述方法会为用户返回 null / undefined。因此,此解决方案适用于您现有的解决方案。因此,在这种情况下,请尝试将现有功能修改为:

async function IsLoggedIn() 
try 
 await new Promise((resolve, reject) =>
  firbase.auth().onAuthStateChanged(
    user => 
      if (user) 
        // Yes User is signed in.
        resolve('User is there');
       else 
        // No user is not signed in.
        reject('There is no user');
      
    ,
    // Prevent console errors
    error => reject(error)
  )
)
return true
 catch (error) 
  return false
 

【讨论】:

【参考方案2】:

此外,由于您打算观察身份验证状态更改,因此您可以在初始化 Firebase 后立即注册侦听器,您不必将其插入到 VueJS watch 块中,您可以将其插入到您的 main.js 块中。例如,如果您使用的是 VueX 之类的商店,则可以更新商店中的状态并从 VueX 应用程序的任何组件中提取该信息。

firebase.initializeApp(configOptions);

firebase.auth().onAuthStateChanged(user => 
    if (user)   
        this.userstate = true;
     else  
        this.userstate = false;
     
);

【讨论】:

以上是关于如何在vue js项目中检测用户的firebase身份验证登录状态?的主要内容,如果未能解决你的问题,请参考以下文章

构建后如何在 Vue.js 项目中存储 Firebase 凭据(env_var)

如何使用 Vue.js Firebase UID 删除用户

如何在验证电子邮件之前阻止 Firebase/Vue.js 中的用户身份验证

如何删除用户点击按钮? - Firebase - Vue.js

Vue.js 和 Firebase “用户”信息

在 Vue.js + Firebase 中设置项目的更好方法是啥? [复制]