【问题标题】:Two direction infinity scroll with Firebase/Firestore backend使用 Firebase/Firestore 后端的两个方向无限滚动
【发布时间】:2018-08-07 04:18:55
【问题描述】:

我想使用 Firestore 作为后端和 Vue.js 作为前端来实现两个方向的无限滚动。我不想从头开始加载完整列表,因为列表可能是巨大的!如果我的方法总体上不好,请告诉我什么是好的。

我的以下代码(只是相关部分)运行良好:

  up() {
    console.log("up()")
    let first = this.items[0]
    console.log("first: ", first.text, first.timestamp)
    db.collection("questions").orderBy("timestamp", "desc").endAt(first.timestamp).limit(this.itemsPerPage).onSnapshot((snapshot) => {
        this.updateItems(snapshot)
    })
  },
  down() {
    console.log("down()")
    let last = this.items[this.items.length - 1]
    console.log("last: ", last.text, last.timestamp)
    db.collection("questions").orderBy("timestamp", "desc").startAt(last.timestamp).limit(this.itemsPerPage).onSnapshot((snapshot) => {
        this.updateItems(snapshot)
    })
  },
  updateItems(snapshot) {
    console.log("updateItems()")
    const temp = []
    snapshot.forEach((item) => {
      temp.push(item.data())
    })
    this.items = temp
  },
  firstLoad() {
    db.collection("questions").orderBy("timestamp", "desc").limit(this.itemsPerPage).get().then((snapshot) => {
      this.updateItems(snapshot)
    })
  }

这是视图的相关部分:

<p>
{{items}}
</p>
<p>
  <a href="#" @click.prevent="up">UP</a>
</p>
<ul v-for="(item, index) in items">
  <li :key="index">#{{index}} {{item}}</li>
</ul>
<p>
  <a href="#" @click.prevent="down">DOWN</a>
</p>

但我不能“向上移动”一个以上的项目,因为 limit() 方法总是从一开始就限制结果集。使用 endAt() 时,有什么方法可以“反转”limit() 方法?这是一个动画 gif,它现在是如何工作的:

不幸的是,动画 gif 不可见,所以这是视频:https://youtu.be/1AR44J92Yg4

【问题讨论】:

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


    【解决方案1】:

    很遗憾,没有 API 可以在 Cloud Firestore 中获取接近范围末尾的固定数量的项目。 Firebase 的实时数据库为此目的有一个 limitToLast,但 Firestore 上不存在该 API。

    您必须使用反向排序顺序创建一个查询,然后对其执行常规limit

    db.collection("questions").orderBy("timestamp").startAt(first.timestamp).limit(this.itemsPerPage)
    

    这意味着您将从该查询中获得与您想要的相反顺序的结果,因此您也必须颠倒将它们添加到 UI 的方式。

    对于这个特定的用例来说,所有这些都相当尴尬,所以我建议使用 filing a feature request 在查询中获取 limitToLast 方法或 reverse 方法。

    如果您有兴趣,这是我用于这些查询的测试平台:https://jsbin.com/dimuvu/edit?js,output

    【讨论】:

    • 感谢您快速而有用的回答! limitToLast 可能很棒,所以我将填写提到的功能请求。
    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2015-05-31
    • 2018-08-24
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多