【问题标题】:How to call a Cloud Function for Firebase in Vue3如何在 Vue3 中为 Firebase 调用云函数
【发布时间】:2021-12-13 10:00:02
【问题描述】:

我正在关注 Net Ninja 关于 firebase 云函数的教程,但我不知道如何从 vue 组件调用函数。 (他在教程中没有使用vue)。

所以我有这个 vue3 应用程序,其中安装了 firebase 功能。如何将函数导入组件?我在任何地方都找不到答案。我还在学习编码,但我仍然不太了解如何导入所需的包。

我在函数文件夹中有一个 index.js 文件,里面有一些函数。 我现在想在单击组件中的按钮时调用其中一个(.onCall 函数)。

我知道我需要在那个组件中导入一些东西,但我不知道是什么!

【问题讨论】:

    标签: javascript node.js firebase vue.js google-cloud-functions


    【解决方案1】:

    您的 Vue.js 应用和 Cloud Functions for Firebase 是整个应用的完全不同的组件。

    Vue.js 应用是一个前端组件(即使它托管在 Firebase Hosting 等云服务中)。

    Cloud Functions 是无服务的后端组件,托管在 Firebase (Google Cloud) 基础架构中并对事件作出反应。

    要让这两个组件相互交互,基本上有两种可能性:

    • 对于 Callable Cloud Functions 和 HTTPS Cloud Functions,您将从 Vue.js 应用程序中调用它们。
    • 对于后台触发的 Cloud Functions(例如,由 Firestore 事件触发,如创建文档),Vue.js 前端可以生成事件(例如,写入 Firestore)和/或侦听 Cloud Functions 执行的结果(例如修改了 Firestore 文档)。

    如何将函数导入组件?

    如上所述,您不能在 Vue.js 代码中集成 Cloud Function 代码。特别是您不能“将功能导入组件”。

    我现在想在单击 a 时调用其中一个(.onCall() 函数) 组件中的按钮。

    如果您的 Cloud Function 是 Callable 的,您可以按照documentation 中的说明通过 JS SDK 调用它。


    更新您的评论:

    documentation 中所述,要从您的 Vue.js 应用程序调用可调用函数,您需要执行以下操作(使用 JS SDK v9):

    将 Firebase 添加到您的 Vue.js 应用中。例如通过firebaseConfig.js 文件:

    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
    import { getFunctions } from "firebase/functions";
    
    const firebaseConfig = {
        apiKey: "...",
        // ....
    };
    
    const firebaseApp = initializeApp(firebaseConfig);
    const db = getFirestore(firebaseApp);
    const functions = getFunctions(firebaseApp);
    
    export { db, functions  };
    

    然后,在你的组件中,你做

    <script>
        import { functions } from '../firebaseConfig';
        import {  httpsCallable } from 'firebase/functions';
        
        // ...
        methods: {
            async callFunction() {
                const addMessage = httpsCallable(functions, 'addMessage');
                const result = await addMessage({ text: messageText })
                const data = result.data;
                //...
            });
                
         }
    
    </script>
    

    【讨论】:

    • 哦哦..我很困惑并删除了我的评论。谢谢!这真的很清楚。我花了一整天的时间试图弄清楚这一点。我也在学习如何使用 firebase 版本 9,所以我有点困惑......但我现在开始更好地理解了。非常感谢你的帮助。今晚我会睡个好觉!
    • @Posoroko 很高兴我能帮助你!如果我的回答给了你解决方案,请采纳。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 2021-02-10
    • 2021-09-13
    • 2020-01-28
    • 2020-11-24
    • 2018-05-17
    • 2017-08-04
    • 2020-08-17
    相关资源
    最近更新 更多