【问题标题】:Get items from a Firebase collection and use them as a list in Vue从 Firebase 集合中获取项目并将它们用作 Vue 中的列表
【发布时间】:2021-08-25 16:19:30
【问题描述】:

我正在为一个学校项目使用 Vue 创建一个简单的网站。上述项目的一部分要求我从 firebase 集合中获取一些数据,以在 Vue 中显示为列表或一组“卡片”。我尝试了一些完全没有成功的事情,有人可以帮助我吗?

这就是我现在正在使用的:

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

我已经验证从数据库中检索数据有效,但是我无法将所述数据从我的 .js 获取到我的 .vue 并让它在 Vue 中显示,并且 console.log 没有显示正确的输出除非它全部放在函数之外。

我最终需要做的是在我的 Vue 页面中列出集合中所有项目的名称(所以我猜是使用 v-for)。我该怎么做?

【问题讨论】:

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


    【解决方案1】:

    要将 Firebase 集合中的项目列出到您的 HTML,请异步检索信息(查询快照)并使用 map() 将每个文档的数据放入 Vue 组件数据中的数组中:

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

    然后,使用“isLoading”属性检查信息是否已经可用于您的 HTML,并使用 v-for 循环遍历您的“miceList”属性。

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

    有关列表渲染的更多信息,请查看 Vue.js 文档:https://vuejs.org/v2/guide/list.html

    【讨论】:

    • 非常感谢您的回答。我试过这个,但它返回错误“'getMice()' is not defined”。我该如何解决?对不起,如果这看起来很明显,但我是一个完全的菜鸟,我一直在试图解决这个问题,但几乎没有成功
    • 使用“this”关键字调用组件“methods”部分的方法。我已经更新了答案。所以那就是:this.getMice() 而不是 getMice()
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 2011-08-28
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多