vue 返回上一页回到原先滚动位置

Fork Me On Github

vue 返回上一页回到原先滚动位置

在一些页面,比如滚动加载的页面默认无法后退保存之前的滚动位置。但需要这个功能该怎么做?

App.vue

html
    
<keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
1234

router

在路由中需加上 keepAlive: true

js
        
{
    name: 'search',
    path: '/search',
    component: Search,
    meta: {
        keepAlive: true, // 需要缓存
    },
}, 
12345678

页面上

在需要的页面 .vue 里加上事件,mounted 事件只在新进入时触发,或离开页面后缓存页面时触发(这时是获取不到任何页面元素的)

js
                
data() {
    return {
        scrollTop: 0,
    };
},
beforeRouteLeave (to, from, next) {
    // this.scrollTop = document.querySelector('.scroll-box').scrollTop; // div内部滚动的
    this.scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    next();
},
beforeRouteEnter(to, from, next) {
    next(vm => {
        // document.querySelector('.scroll-box').scrollTop = vm.scrollTop;// div内部滚动的
        document.body.scrollTop = vm.scrollTop;
    });
},
12345678910111213141516

注意:以上事件只能放到页面上面,不能放到页面上的部件里

参考

  1. vue返回上一页面时回到原先滚动的位置
点击查看全文
标签: vue
0 942 0
升级vue3记录
2021年08月
最近有空折腾一下vue3,把以前的vue项目从vue2升级到vue3
玩转vue和小程序
vue 实现左滑删除,右滑点赞,一个滑动其他的复原!
Vuex 使用心得
2019年03月
Vuex 使用心得,typescript版。