如何在Vue3项目中调用Firebase Cloud Function云函数
Vue3 调用 Firebase onCall 类型云函数的操作步骤
前置准备
- 先确认你的Vue项目根目录(注意不是
functions服务端目录)已经安装Firebase Web SDK,未安装的话运行命令:npm install firebase - 你
functions/index.js里编写的onCall类型云函数已经部署到Firebase服务器,部署方式为在functions目录下运行命令:firebase deploy --only functions
注意:
functions文件夹内的所有代码都是服务端代码,仅需部署到Firebase服务器,前端不需要导入该文件夹下的任何本地文件
第一步:编写Firebase全局配置文件
在Vue项目的src目录下新建firebase.config.js,写入以下内容,替换成你自己的Firebase项目配置参数(参数可在Firebase控制台项目设置页获取):
// 导入Firebase核心和需要的模块 import { initializeApp } from "firebase/app"; import { getFunctions } from "firebase/functions"; const firebaseConfig = { apiKey: "你的项目apiKey", authDomain: "你的项目authDomain", projectId: "你的项目projectId", storageBucket: "你的项目storageBucket", messagingSenderId: "你的项目messagingSenderId", appId: "你的项目appId" }; // 初始化Firebase const app = initializeApp(firebaseConfig); // 初始化并导出functions实例,后续调用云函数都用这个实例 export const functions = getFunctions(app);
第二步:在Vue组件中调用云函数
假设你部署的onCall云函数名称为sendNotification,组件内调用示例如下:
<template> <button @click="callCloudFunction">点击调用云函数</button> </template> <script setup> // 导入第一步导出的functions实例,以及云函数调用方法 import { functions } from '@/firebase.config.js' import { httpsCallable } from 'firebase/functions' const callCloudFunction = async () => { try { // 绑定要调用的云函数名称 const sendNotification = httpsCallable(functions, 'sendNotification') // 调用云函数,可传入自定义参数,云函数端可通过data字段拿到该参数 const result = await sendNotification({ userId: '123', content: '测试内容' }) // 打印云函数返回的结果 console.log('调用成功,返回结果:', result.data) } catch (error) { // 捕获调用错误 console.error('调用云函数失败:', error) } } </script>
内容的提问来源于stack exchange,提问作者Posoroko
相关产品推荐
相关产品推荐

