javascript - 带有 Firebase/Firestore 后端的双向无限滚动

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

我想使用 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)
    })
  }

这里是 View 的相关部分:

<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,它现在是如何工作的: enter image description here

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

最佳答案

不幸的是,在 Cloud Firestore 中,没有 API 可以获取接近范围末尾的固定数量的项目。 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

关于javascript - 带有 Firebase/Firestore 后端的双向无限滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49010025/

相关文章:

javascript - 在 phantomjs 中没有用于 document.register 的 polyfill

键盘可见时的 Swift iOS ScrollView

jQuery 高速滚动时滚动计算不准确

javascript - 我应该如何格式化 JSON 并向我解释一些基本的 d3 图节点链接?

javascript - Screeps 很少有错误/问题

javascript - 在不重新加载页面的情况下更改 html 内容和 url

ios - Firebase 检测电子邮件验证

firebase auth 是否可以限制某些用户的登录?

firebase - Firestore 安全规则。用户可以知道别人的 UID 吗?

android - 如何在 Google Glass X16 固件的简单适配器上启用滚动