在Vue.js中加载更多数据时,保持在相同的垂直坐标

问题描述

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

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

解决方法

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

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

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

  3. 在加载了新内容之后,调用scrollTo方法以滚动至其在nextTick回调中在步骤2中获得的位置

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>