【问题标题】:How to use 9.0.1 Firebase methods with VueJS 3如何在 VueJS 3 中使用 9.0.1 Firebase 方法
【发布时间】:2021-11-01 13:02:33
【问题描述】:

我是 Vue 的新手,这是我要学习的第二个教程,它将 firebase 后端与 Vue 集成。但是本教程使用的是 Vue 2 和旧版本的 firebase,所以我想我可以尝试使用 Vue 3 和新的 Firebase 版本。

firebase 9.0.1 上的资源至少在使用 Vue 实现方面似乎相当有限。这是我从有关signInAnonymously的firebase文档中找到的

import { getAuth, signInAnonymously } from "firebase/auth";

const auth = getAuth();
signInAnonymously(auth)
  .then(() => {
    // Signed in..
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ...
  });

据我了解,firebase 9.0.1 是仅导入您使用的样式?所以如果我想使用 firebase/auth 中的 getAuthsignInAnonymously 方法,我会这样做

import { getAuth, signInAnonymously } from 'firebase/auth';

但我对如何使用 .Vue 文件中的方法有点困惑 所以我在 firebase.js 文件中所做的是

export const auth = getAuth();
export {signInAnonymously};

然后在我的Login.vue 文件中,我做到了

import { auth, signInAnonymously } from '../firebase'

export default {
    data() {
        return { auth }
    },
    methods: {
        signInAnonymously
    }
}

我有一个按钮,点击后会触发signInAnonymously,它是这样写的

<button class="button" @click="signInAnonymously(auth)">Sign In</button>

我写的东西似乎有效,但我觉得它有点令人费解/困惑,想知道

  1. 我这样做是否正确,或者是否有更短/更简洁的方式来编写代码?
  2. 如果我想修改signInAnonymously 方法,如firebase 文档中所示,即添加那些signInAnonymously(auth).then(() =&gt; {}),会发生什么,因为如果我要在导出默认值中添加signInAnonymously 的参数,如下所示,它不将其识别为我的 firebase.js 文件中的导出方法?

export default {
 ...,
 methods: {
   signInAnonymously(auth) {
     ...
 }
}

【问题讨论】:

    标签: javascript firebase vue.js firebase-authentication vuejs3


    【解决方案1】:

    尝试创建一个自定义方法并在其中使用signInAnonymously(),如下所示:

    import { auth } from '../firebase'
    import { signInAnonymously } from 'firebase/auth'
    // can be imported directly in Login.vue ^^
    
    export default {
      methods: {
        anonymousLogin() {
          // Directly pass 'auth' in this method
          signInAnonymously(auth)
            .then(() => {
              // Signed in..
            })
            .catch((error) => {
              const errorCode = error.code;
              const errorMessage = error.message;
              // ...
            });
        },
      },
    };
    

    然后在@click事件中使用这个自定义方法:

    <button class="button" type="button" @click="anonymousLogin">Sign In</button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 2021-06-09
      • 2018-03-02
      • 1970-01-01
      • 2017-03-12
      • 2021-04-15
      相关资源
      最近更新 更多