最近用 Vue 做移动端页面遇到一个问题,从列表页进入详情页,再返回到列表页,不管之前滚动到哪里,每次返回时都跳到列表最顶部。这样体验肯定不好,期望的应该是记住滚动条的位置,每次返回还是在原来的位置上,便于继续浏览。
1.返回不刷新使用keepAlive。(多级路由/菜单会导致keepAlive失效)
$route(to, from){ if (to.meta.keepAlive){ !this.include.includes(to.meta.name)&&this.include.push(to.meta.name); } if (from.meta.keepAlive && to.meta.deepth < from.meta.keepAlive){ //清空from缓存,除了首页以外 if (from.name === 'home'){ return ; } let index = this.include.indexOf(from.meta.name); index !== -1 && this.include.splice(index, 1); } if(to.meta.name&&to.meta.name.indexOf('handle')!=-1){//解决进入操作页返回不刷新问题 this.include = [] } }
2.在离开当前页面时获取当前滚动条高度。因为设置了keepAlive,所以可以在data中设置一个变量存储。
(ref加在产生滚动的那个容器上)
3.返回当前页面时在activated周期中设置保存的高度。
activated() { this.$refs.wrapper.scrollTop = this.scrollTop; },