有个需求就是切换tab后,原先的table水平滚动条要还原位置(如下图),先说下思路,大致就是 切出页面时 把滚动距离保存到Storage 中,切回来时在恢复
 
 直接上代码
 首先table ref指定一下ref="jtable"
 vue methods中写好两个方法
handleScroll() { //滚动的事件
        let scrollPosition = this.$refs.jtable.$el.querySelector('.ant-table-body').scrollLeft;
        localStorage.setItem("PortMore-scrollLeft", scrollPosition);
    },
    //定位到原来滚动条的位置
    restoreScrollPosition() {
        let scrollX = localStorage.getItem('PortMore-scrollLeft');
        if (scrollX) {
            this.$refs.jtable.$el.querySelector('.ant-table-body').scrollLeft = scrollX;
        }
    },
 
注意,如果是只涉及几个页面,可以像我一样直接指定存入localStorage中的key是PortMore-scrollLeft,多个的话可以通过路由路径去拼接,比如localStorage.setItem(this.$route.fullPath+"-scrollLeft", scrollPosition);
 接下来就是几个触发事件
watch: {
	//路由变更的时候恢复保存的滚动位置
    '$route'(nv, ov) {
         this.restoreScrollPosition();
    },
  },
  beforeDestroy() {
     // 页面关闭前触发的逻辑
     localStorage.removeItem("PortMonitor-scrollLeft");
  },
 
如果你的tab页面很简单的话,推荐使用这个方法
beforeRouteLeave(to, from, next) {
        this.handleScroll();
        //指定操作要放在离开路由前
        this.routeThis = this.$route.fullPath;
        next();
    },
 
注意,这时候你会发现beforeDestroy获取不到之前的路由,所以我是这样拼接的
beforeDestroy() {
        // 页面关闭前触发的逻辑
        localStorage.removeItem(this.routeThis + "-scrollLeft");
    },
 
这个routeThis是定义在上边data里的
data() {
        return {
            routeThis: "",
        };
    },
 
但是,如果你的tab页面里又套了两个小tab页面,建议老老实实在小页面mounted里写上以下代码
this.$nextTick(() => {
       const tableComponent = this.$refs.jtable;
       if (tableComponent) {
          const tableContainer = tableComponent.$el.querySelector('.ant-table-body');
          tableContainer.addEventListener('scroll', this.handleScroll);
       }
    })
 
这个是给table加上一个滚动监听事件



















