【问题标题】:How to display Firebase array items in Vue.js如何在 Vue.js 中显示 Firebase 数组项
【发布时间】:2020-01-08 19:29:39
【问题描述】:

我正在构建一个 Vue.js 应用程序,该应用程序使用户能够将项目添加到已在 Firebase 文档中设置的数组中。将项目添加到数据库中的数组的函数工作正常。我想将数组中的项目作为屏幕上的列表项返回。但是,目前,整个数组容器都返回到屏幕上。如何重新设置它的样式,以便在没有容器的情况下将数组项很好地呈现为列表项?最好使用 Vuetify。谢谢!

模板

<v-list class="elevation-1">
  <v-list-tile-content v-for="user in this.$store.getters.getUsers" :key="user.id" >
    <v-list-tile>
      {{ user.events }}
    </v-list-tile>
  </v-list-tile-content>
</v-list>

方法

    async addInput () {
      let finalInput = this.newInput
      let ref = await db.collection('users').where('user_id', '==', firebase.auth().currentUser.uid)
      .get()
      .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
          console.log(doc.id, " => ", doc.data());
          doc.ref.update({'events': firebase.firestore.FieldValue.arrayUnion(finalInput)})
        })
      })
      .catch(function(error) {
        console.log("Error getting documents: ", error);
      });
    }

【问题讨论】:

    标签: javascript firebase vue.js vuex vuetify.js


    【解决方案1】:

    好的,这就是我最终想要实现的目标。我重新配置了 addInput 方法,将输入的数据作为对象推送到数组中。然后我添加了第二个循环两个模板,它遍历数组 user.events 中的项目并将它们作为列表项返回。这行得通!见下文:

    模板

    <v-list class="elevation-1">
      <v-list-tile-content>
        <v-list-tile v-for="user in this.$store.getters.getUsers" :key="user.id">
          <v-list-tile v-for="newUser in user.events">
            {{ newUser.name }}
          </v-list-tile>
        </v-list-tile>
      </v-list-tile-content>
    </v-list>
    

    方法

    async addInput () {
      let finalInput = this.newInput
      let ref = await db.collection('users').where('user_id', '==', firebase.auth().currentUser.uid)
      .get()
      .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
          console.log(doc.id, " => ", doc.data());
          doc.ref.update({'events': firebase.firestore.FieldValue.arrayUnion({
            'name': finalInput
          })
        })
      })
    })
    .catch(function(error) {
      console.log("Error getting documents: ", error);
    });
    }
    

    【讨论】:

      【解决方案2】:

      v-for 属性应该在 item 元素中声明,而不是在包含元素中。为此,请将v-for 移动到列表项元素中,如下所示:

      <v-list class="elevation-1">
        <v-list-tile-content v-for="user in this.$store.getters.getUsers" :key="user.id">
          <v-list-tile v-for="event in user.events">
            {{ event }}
          </v-list-tile>
        </v-list-tile-content>
      </v-list>
      

      【讨论】:

      • 感谢您的反馈。不幸的是,这并没有奏效。数组中的项是“事件”的子项。有什么我需要添加到{{ user.events }} 以使 for 循环遍历数组项而不是整个数组吗?
      • @JS_is_awesome18 这对您正在寻找的东西有用吗?循环遍历每个用户以创建他们的事件列表?
      • 是的,我已经知道了,但感谢您的入住。非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2015-05-27
      • 2021-02-23
      • 1970-01-01
      • 2018-06-01
      • 2021-08-30
      • 2020-06-05
      • 1970-01-01
      • 2021-02-06
      相关资源
      最近更新 更多