vue项目keep-alive返回记住滚动条位置

需求:点击首页列表进入二级页面,返回的时候保持在原位置。
keep-alive是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。

1:App.vue

<template>
    <div id="app">
        <!--页面返回不刷新-->
        <!-- // 缓存组件跳转的页面 -->
        <keep-alive>
            <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <!-- // 非缓存组件跳转页面 -->
        <router-view v-if="!$route.meta.keepAlive"></router-view>
    </div>
</template>

2:router / index.js

export default new Router({
    routes: [
        {
          path: '/',
          name: 'home',
          component: Home,
          meta: {
            keepAlive: true // 需要缓存
          }
        },{
          path: '/home',
          name: 'home',
          component: Home,
          meta: {
            keepAlive: true // 需要缓存
          }
        },
        ...
       ]
       scrollBehavior(to, from, savedPosition) { //解决拖动时多个页面互相影响的问题,当切换到新路由时,想要页面滚到顶部
      // if (savedPosition) {
      //   return savedPosition
      // } else {
      //     if (from.meta.keepAlive) {
      //       from.meta.savedPosition = document.body.scrollHeight
      //     }
      //   }
        // return {
        //     x: 0,
        //     y: 0
        // }
    }
 })

3:home.vue
3.1:定义初始滚动高度

data() {
    return {
        scrollY:0,
    }
},

3.2:注意这里一定是滚动的元素是

.container
.container {
        position: absolute;
        top: 0;bottom: 0;
        width: 100%;
        padding: 0;margin:0;
        overflow: hidden;
        overflow-y: scroll;
    }

3.3:重点!! (不用放在methods里)

//记录离开时的位置
beforeRouteLeave (to, from, next) { 
     //保存滚动条元素div的scrollTop值
     this.scrollY = document.querySelector('.container').scrollTop
     // console.log(this.scrollY)    
    next()
 },
// 为div元素重新设置保存的scrollTop值
beforeRouteEnter (to, from, next) {
      next(vm => {  // vm = this
          document.querySelector('.container').scrollTop = vm.scrollY
          // console.log( document.querySelector('.container').scrollTop )
      })
},

本人在移动端亲测代码: 亲测有效,一定要弄清楚是哪个元素在滚动,不要直接用winodow去监听,直接用滚动的元素去监听才能监听到scrollTop

html:

<div class="newVipClass" >
<div class="recordContent"> <!--这个才是滚动元素元素需要监听,scrollTop才能获取到,我最外面的元素是fiexed定位的,永远获取不到scroll-->
...
</div>
</div>

js:

data: {
    box: '',
    scrollY: ''
}

mounted: {
  // 监听scroll变化
   this.$nextTick(()=>{
        this.box = document.querySelector('.recordContent')
        this.box.addEventListener('scroll', function(){
          this.scrollY = document.querySelector('.recordContent').scrollTop
          console.log("scrollY", this.scrollY)
        }, false)
      })   
},
beforeRouteEnter (to, from, next) {
      next(vm => {
        //因为当钩子执行前,组件实例还没被创建
        // vm 就是当前组件的实例相当于上面的 this,所以在 next 方法里你就可以把 vm 当 this 来用了。
        console.log(vm);//当前组件的实例
        if (from.name == 'monthCarApplyDetal' && to.name == "newMonthApply") {
          to.meta.title = "编辑月卡申请"
        }
        // 为div元素重新设置保存的scrollTop值
        document.querySelector('.recordContent').scrollTop = vm.scrollY 
      });
    },
    //记录离开时的位置
    beforeRouteLeave (to, from, next) { 
        //保存滚动条元素div的scrollTop值
        this.scrollY = document.querySelector('.recordContent').scrollTop
        console.log('离开时保存滚动条的位置', this.scrollY)    
      next()
    },

小伙伴们还有啥好方法,欢迎分享!!!

原文地址:https://www.cnblogs.com/mmzuo-798/p/12901425.html