简体   繁体   中英

How to produce data after getting firebase firestore in Vue.JS

I want to show all of the orders data that I get from firebase to my browser console. Please look at the picture below

在此处输入图片说明

this is the data which get from firebase after written some codes like below in cue.js

orders(){
    const db = firebase.firestore();
    const dbOrderRef = db.collection('order');
    dbOrderRef.get()
        .then(res => {
            res.forEach(doc => {
                console.log(doc.data())
            })
        })
        .catch(err => {
            console.log('error', err)
        })
}

I have tried to like this below

The instance variable in data

ordersData = []

then in method

this.ordersData = doc.data()

but no luck.

What can I do for now to achieve my goal?

Thanks

If I understand correctly your question, you want to assign to an ordersData Array all the orders received from a Firestore query.

The following should do the trick:

const db = firebase.firestore();
const dbOrderRef = db.collection('order');

let orderArray = [];
dbOrderRef.get()
    .then(res => {
        res.forEach(doc => {
            let orderObj = doc.data();
            orderObj.id = doc.id;
            orderArray.push(orderObj);
        });
        this.ordersData = orderArray;
    })
    .catch(err => {
        console.log('error', err)
    })

Then you can display the ordersData array in your template as follows, for example:

            <div v-if="ordersData.length">
                <div v-for="order in ordersData">
                    <h5>{{ order.name }}</h5>
                    <p>Price: {{ order.price }}</p>
                    <p>
                     <a @click="openOrderDetail(order.id)">Open order</a>  
                     // Here we show how we can call an openOrderDetail() method passing the Firestore document id of the order.
                     // This would allow, for example to route to a page where you use the order id to query for the order document.
                    </p>
                </div>
            </div>

While working with then , this keyword used inside the then block refers to the block itself and not the Vue object. The following solution should work as the orders function, in which we save the Vue reference in another variable and use this variable to access ordersData.

let _this = this
const db = firebase.firestore();
const dbOrderRef = db.collection('order');
dbOrderRef.get()
    .then(res => {
        res.forEach(doc => {
            _this.ordersData = doc.data();
            console.log(_this.ordersData)
        })
    })
    .catch(err => {
        console.log('error', err)
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM