【问题标题】:Getting Firestore data as Javascript object将 Firestore 数据作为 Javascript 对象获取
【发布时间】:2021-10-12 10:07:15
【问题描述】:

我正在尝试从 Google Firestore 获取数据作为 Vue.js (3) 中的 javascript 对象。 在 V-for 中使用数据时它工作得很好,但我也想在方法中使用数组。 如何将 Firestore 中的这些数据转换为简单的 Javascript 对象? 我试过使用JSON.parse(),但这不起作用。

这是我得到的数据:

使用此代码:

<template>
  <section>
    <div id="testWrapper">
        <div>
            <p>{{ list }}</p>
        </div>
    </div>
  </section>
</template>

<script>
import { useLoadClients } from "../../firebase.js";


export default {
    data(){
        return{
            list:[]
        }

    },
    async mounted(){
        const newList = await useLoadClients()
        this.list= newList
    }
}
</script>

这是 Firebase 配置(显然是审查了 Api 密钥):

import firebase from "firebase/app";
import "firebase/firestore";
import { ref, onUnmounted } from "vue";

const config = {
  apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  authDomain: "hourly-3295e.firebaseapp.com",
  databaseURL:
    "https://hourly-3295e-default-rtdb.europe-west1.firebasedatabase.app",
  projectId: "hourly-3295e",
  storageBucket: "hourly-3295e.appspot.com",
  messagingSenderId: "434096768140",
  appId: "1:434096768140:web:16bca36e806af1d7e027a9",
  measurementId: "G-XMHZQHM81H",
};

const firebaseApp = firebase.initializeApp(config);

const db = firebaseApp.firestore();
const clientCollection = db.collection("clients");

export const createClient = (client) => {
  return clientCollection.add(client);
};

export const getClient = async (id) => {
  const user = await clientCollection.doc(id).get();
  return user.exists ? user.data() : null;
};

export const updateClient = (id, client) => {
  return clientCollection.doc(id).update(client);
};

export const deleteClient = (id) => {
  return clientCollection.doc(id).delete();
};

export const useLoadClients = () => {
  const clients = ref([]);
  const close = clientCollection.onSnapshot((snapshot) => {
    clients.value = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
  });
  onUnmounted(close);
  return clients;
};

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore


    【解决方案1】:

    Snapshot.data() 已经是一个 Javascript 对象,您的应用程序将其呈现为文本,因为您在文本元素中打印它。 如果您仍需要将其从文本转换为对象,您可以使用JSON.parse(jsonString)

    我也强烈推荐使用typeof snapshot.data(),它会返回一个与其类型相同的字符串值,在本例中是"string""Object"

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 2018-10-14
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多