让el-table长个小脑袋,记住我的滚动位置

177 阅读1分钟

需求来源:
需求师:我说,老牧你这个页面再调整一下呗,我希望这个滚动条从详情页返回来的时候还能保持再当时的位置,你看这老是给我刷新置顶好麻烦。
我:行都行的,你是老大你说的算。(等着等我骑到你头上)【心理活动】

首先,我去网上查了一下(没做过先看看有没有现成的案例)。看了一圈大概都是keep-alive+data中的字段进行辅助。ok搞起!!!!!

第一步:keep-alive配置

<template>
    <div>
        <keep-alive>
            <router-view v-if="alivePath.includes($route.path)"></router-view>
        </keep-alive>
        <router-view v-if="!alivePath.includes($route.path)"></router-view>
    </div>
</template>
data(){
    return{
        alivePath:["/projectMaintenance"],
    }
}

第二步:对应页面位置记录

data(){
  return{
    scrollTop:0,
  }
},
methods:{
  restoreScroll() {
    if (this.scrollTop > 0) {
      setTimeout(() => {
        this.$refs.multipleTable.bodyWrapper.scrollTop=this.scrollTop
      }, 100);
    }
  },
},
activated() {
  // 当组件被重新激活时,恢复滚动位置
  this.$nextTick(() => {
    this.restoreScroll();
  });
},
beforeRouteLeave(to, from, next) {
  // 在离开前保存滚动位置
  if (this.$refs.multipleTable) {
    this.scrollTop = this.$refs.multipleTable.bodyWrapper.scrollTop;
  }
  next();
}

就这么点代码,你没看错哈哈哈哈。
有些地方我知道可能我写的不够好,所以我想说以上内容仅供参考