vue中重新获取数据导致页面加长,要求在页面更新之后浏览器滚动条滚动到之前浏览记录的位置。以及获取当前页面中是哪个元素产生滚动条的方法。

目前的页面样式为:

 代码是:

  <section id="detailSection">
    <el-table
      ref="multipleTable"
      :data="logDetailList"
      style="width: 650px;margin:20px auto;"
      id="dialogDetail"
      :show-header="false"
      :cell-style="cellStyle"
      v-loading="formLoading"
    >
      <el-table-column
        class="log-detail-origin_timestamp"
        prop="_source.origin_timestamp"
        label="时间"
        width="185"
      ></el-table-column>
      <el-table-column class="log-detail-msg" label="查询的log">
        <template slot-scope="props">
          <el-button
            class="asidebtn-up"
            v-if="props.$index == 0"
            type="primary"
            @click="searchUp"
          >向上查询</el-button>
          <el-button
            class="asidebtn-down"
            v-if="props.$index == logDetailList.length - 1"
            type="primary"
            @click="searchDown"
          >向下查询</el-button>
        </template>
      </el-table-column>
    </el-table>
  </section>

首先获取当前el-table的高度(此处$refs后的multipleTable是在el-table中用ref绑定的值)

 let positionHeight = this.$refs.multipleTable.bodyWrapper.scrollHeight;

其次用接口获取新数据(也就是更新logDetailList里的值),将新数据渲染到页面中。

最后用$nextTick方法在数据渲染完成之后的滚动条定位定到之前的位置上。

(1)获取新数据的el-table长度

let positionHeight2 = this.$refs.multipleTable.bodyWrapper.scrollHeight;

(2)长度相减。新数据页面的长度-旧数据页面长度=当前滚动条滚动位置

let screenHeight = positionHeight2 - positionHeight;

(3)设置滚动条位置。注:scrollTo方法必须是该页面存在滚动条的元素。且必须是el-table的父元素。

document.querySelector(".content-container").scrollTo(0, screenHeight);

这样就完成了。

扫描二维码关注公众号,回复: 16433359 查看本文章

附加 :

获取当前页面中是哪个元素产生滚动条的方法(vue中):页面滚动后控制台会打印

methods: {    
  findscroller(element) {
    element.onscroll = function() {
      console.log(element);
    };
  Array.from(element.children).forEach(this.findscroller);
 }
}
mounted() {
  this.findscroller()
}

 或者直接复制以下代码到控制台中。回车,拖动滚动条

function findscroller(element){
  element.onscroll=function () {
    console.log(element)
  }
  Array.from(element.children).forEach(findscroller)
}
findscroller(document.body)

猜你喜欢

转载自blog.csdn.net/qq_56715703/article/details/131924471