【发布时间】: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