Vue 路由跳转记住滚动位置,返回时回到上次滚动的位置

这是一个实现上拉加载和下拉刷新功能的页面,这里用了vue-infinite-scroll插件,需要实现返回页面时页面可以自动滑动到上次滑动的位置。具体实现方式如下:
1、在App.vue文件中设置缓存组件keep-alive

<!-- 缓存组件跳转的页面 -->
 <keep-alive> 
  <router-view v-if="$route.meta.keepAlive" transition-mode="out-in"></router-view>
 </keep-alive>
<!-- 非缓存组件跳转页面 -->
<router-view v-if="!$route.meta.keepAlive" transition-mode="out-in"></router-view>

2、路由文件中给需要记录滚动位置的页面设置keepAlive: true

{
  path: '/Info',
  name: 'InfoList',
  component: InfoList,
  meta: {
    keepAlive: true
  }
}

3、在页面注册对应的事件
(1)在data中定义一个初始值 scroll
(2)在mouted中 ,mouted中的方法代表dom已经加载完毕

mounted() {
  window.addEventListener('scroll', this.handleScroll)
}

(3)methods 用于存放页面函数

handleScroll () {
  this.scroll  = document.documentElement && document.documentElement.scrollTop
  console.log(this.scroll)
}    

4、activated 为keep-alive加载时调用

activated() {
  if(this.scroll > 0) {
    window.scrollTo(0, this.scroll); this.scroll = 0;
    window.addEventListener('scroll', this.handleScroll);
  }
}

5、deactivated 页面退出时关闭事件 防止其他页面出现问题

deactivated(){
  window.removeEventListener('scroll', this.handleScroll);
}

\color{#ea4335}{注意:}keep-alive和上拉加载组件infinite-scroll一起使用时,其他子组件会触发infinite-scroll
\color{#ea4335}{解决方法:}在deactivated里面将属性infinite-scroll-disabled设置为true

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容