gpt4 book ai didi

javascript - 如何在 Vue3 中为 Firebase 调用云函数

转载 作者:行者123 更新时间:2023-12-02 01:54:51 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

Vue.js 应用程序是一个前端组件(即使它托管在像 Firebase Hosting 这样的云服务中)。

Cloud Functions 是无服务的后端组件,托管在 Firebase(谷歌云)基础架构中并对事件使用react。

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

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

How do I import the functions into a component?

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

I now want to call one of them (a .onCall() function) when clicking abutton in a component.

如果您的 Cloud Functions 是可调用函数,您可以通过 JS SDK 调用它,如 documentation 中所述。 .


更新您的评论:

documentation 中所述, 要从您的 Vue.js 应用程序调用 Callable Function,您需要执行以下操作(使用 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>

关于javascript - 如何在 Vue3 中为 Firebase 调用云函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69750038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com