Firebase 9 和 ref 函数与 Vue 组合

jdo*_*_26 2 javascript firebase vue.js firebase-storage

我想将图像上传到 firebase storage,版本 9。我有 firestore 的工作代码,但我一生都无法理解有关上传的 firebase 文档,以及如何使其适用于 Vue (这也需要导入REF 函数)。

我的问题是:如何在 Vue 中导入 ref 函数,以及如何导入和使用 firebase firestore 中的 ref 函数?

这就是我所拥有的。用 .value 包装 Firebase ref 感​​觉不对,但我只是将它放在那里以克服 vue 错误。

vue 组件代码片段:<-- 这有效

if (imageFile.value) {
        await uploadImage(imageFile.value);
        console.log("image:" + url.value);
      }
Run Code Online (Sandbox Code Playgroud)

useStorage.js <--这是尝试从 Firebase 8 转换为 9 时一切都崩溃的地方。它是 vue Ref 函数吗?

import { ref } from "vue";
import { projectStorage } from "../firebase/config";
import { uploadBytesResumable, getDownloadURL } from 
"@firebase/storage";


const useStorage = () => {
const error = ref(null);
const url = ref(null);
const filePath = ref(null);
  
 //I need to use ref with firestore here
 const uploadImage = async (file) => {
    filePath.value = `images/${file.name}`;
    const storageRef = ref(projectStorage, 
  filePath.value).value;


   try {
     const res = await storageRef.put(file);
     url.value = res.ref.getDownloadURL();
   } catch (err) {
     console.log(err.message);
     error.value = err.message;
   }
 };

return { url, filePath, error, uploadImage };
};

export default useStorage;
Run Code Online (Sandbox Code Playgroud)

配置文件

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  [info]
};

// init firebase
const firebaseApp = initializeApp(firebaseConfig);

// init firestore service
const db = getFirestore(firebaseApp);

// init firestore authorization
const auth = getAuth(firebaseApp);


const projectStorage = getStorage(firebaseApp);



export { db, projectStorage, auth };
Run Code Online (Sandbox Code Playgroud)

Dha*_*raj 9

您可以为任一导入设置别名,如下所示:

import { ref } from "vue";
import { projectStorage } from "../firebase/config";
import { ref as storageRef } from "@firebase/storage";


const fileRef = storageRef(projectStorage, filePath.value);
// use storageRef here ^^^ instead of ref from vue
Run Code Online (Sandbox Code Playgroud)

另请查看:如何在 javascript/es6 中导入两个同名的类?