Luca Isabella
Luca Isabella

Reputation: 1

Get items from a Firebase collection and use them as a list in Vue

I am creating a simple website using Vue for a school project. One part of said project requires me to get some data from a firebase collection to show as a list or as a set of "cards" in Vue. I have tried a few things with absolutely no success at all, can anyone help me?

This is what I'm working with right now:

mouseRef = db.collection("Mice");

export default {
  getMice: function () {
    var output = mouseRef.get().then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
          console.log(doc.id, " => ", doc.data());
          return (doc.id, " => ", doc.data());
      });
    });
return output;
  },
};

I have verified that retrieving data from the database works, however I can't get said data from my .js to my .vue and get it to show in Vue, and the console.log doesn't show the right output either unless it's all put outside the function.

What I ultimately need to do is list the name of all items from the collection in my Vue page (so I guess using v-for). How can I do that?

Upvotes: 0

Views: 1475

Answers (1)

Eli
Eli

Reputation: 183

To list items from a Firebase Collection to your HTML, retrieve asynchronously the information (query snapshot) and use map() to put each document's data into an array in your Vue component's data:

<script>
import firebase from 'firebase/app'
import 'firebase/firestore'

export default {
  data() {
    return {
      miceList: [],
      isLoading: false
    }
  },
  mounted() {
    // Get mice on component mount
    this.getMice() // edit
  },
  methods: {
    getMice() {
      this.isLoading = true

      firebase.firestore()
        .collection("mice")
        .get()
        .then((querySnapshot) => this.miceList = querySnapshot.docs.map(doc => doc.data()))
        .finally(() => this.isLoading = false);
    },
  }
};
</script>

Then, use the "isLoading" property to check if the information is already available for your HTML, and loop through your "miceList" property with v-for.

<template>
  <div>
    <div v-if="isLoading">
      Loading...
    </div>
    <div v-else>
      <div v-for="(mouse, index) in miceList" v-bind:key="index + '-mouse'">
        Mouse example {{ index }}: {{ mouse.name }}
      </div>
    </div>
  </div>
</template>

For more on List Rendering check Vue.js documentation: https://v2.vuejs.org/v2/guide/list.html

Upvotes: 1

Related Questions