【问题标题】:Firebase 9 and ref function with Vue compositionFirebase 9 和带有 Vue 组合的 ref 函数
【发布时间】:2022-01-10 16:54:30
【问题描述】:

我想将图像上传到 firebase 存储,版本 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);
      }

useStorage.js

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;

config.js

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 };

【问题讨论】:

    标签: javascript firebase vue.js firebase-storage


    【解决方案1】:

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

    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
    

    也结帐:How to import two classes by the same name in javascript/es6?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 2015-12-29
      • 2021-03-13
      相关资源
      最近更新 更多