【问题标题】:Remain at the same vertical coordinate when loading more data in Vue.js在 Vue.js 中加载更多数据时保持相同的垂直坐标
【发布时间】:2020-12-17 19:06:54
【问题描述】:

我有一个加载更多按钮,可以将更多数据加载到组件中。但是,在按下加载按钮后,用户会在屏幕底部滚动,因为加载更多按钮也位于屏幕底部。

用户必须向上滚动才能看到加载的内容。有什么办法可以让用户在按下按钮时保持在同一个垂直坐标上?

【问题讨论】:

  • 所以加载的内容在页面顶部?如果是这样,为什么不将加载的内容放在页面底部?你能发布你已经尝试过的代码吗?

标签: javascript vue.js vue-directives


【解决方案1】:

如果您想滚动到 Load More 按钮所在的原始位置,一个解决方案:

  1. 使用ref标记相关的VNode(滚动容器ref=container和锚点ref=test

  2. Load Button被按下时,获取当前按钮位置

  3. 新内容加载完成后,调用scrollTo方法滚动到nextTick回调中第二步得到的位置

new Vue ({
  el:'#app',
  data () {
    return {
      rows: Array.from({length: 100}).map((_, index) => index),
      current: 5,
      currentCoords: {top: 0, left: 0}
    }
  },
  computed: {
    computedRows: function () {
      return this.rows.slice(0, this.current)
    }
  },
  methods: {
    loadMore: function () {
      this.currentCoords.top = this.$refs.test.offsetTop
      this.currentCoords.left = this.$refs.test.offsetLeft
      this.current += 15
      this.$nextTick(() => {
        this.$refs.container.scrollTo(this.currentCoords.left, this.currentCoords.top - 10)
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
    <div class="container">
        <div ref="container" style="max-height: 200px;overflow:auto">
            <p v-for="(row, index) in computedRows" :key="index">{{row}}</p>
            <button ref="test" @click="loadMore()">Load More</button>
        </div>
    </div>
</div>

【讨论】:

  • 我不得不稍微调整一下以使其适用于我的场景。但是,感谢您让我了解 $nextTick 功能。这是让它发挥作用的关键。我没有放任何参考。我只是将 x 和 y 位置存储在加载更多方法(var xLastPosition = window.pageXOffset)中。然后在 nextTick 方法中,我使用了 window.scroll(xLastPosition, yLastPosition);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 2020-08-22
  • 2017-12-27
  • 1970-01-01
  • 2016-06-02
相关资源
最近更新 更多