1、在想要缓存滑动高度的页面加入一下代码
beforeRouteLeave(to, from, next) {
this.$route.meta.scrollHeight = document.documentElement.scrollTop
next();
}
切换路由之前获取页面的高度,并存入当前路由的meta中(scrollHeight为自定义key)
2、存入滑动高度后,在路由管理页面(Router下的index.js页面)加入路由跳转监听
router.beforeEach((to, from, next) => {
next();
if(to.meta.scrollHeight) {
document.documentElement.scrollTop = to.meta.scrollHeight
}
})
查看将要跳转的路由(to)是否含有scrollHeight这个字段,如果有就改变页面高度,没有就跳过
如果出现部分页面不生效需要用setTimeout把document.documentElement.scrollTop = to.meta.scrollHeight包起来
setTimeout(()=>{
document.documentElement.scrollTop = to.meta.scrollHeight
})
3、这种方法适用于可以获取到 document.documentElement.scrollTop 的项目,如果项目整个页面的根节点是position定位后固定为height: 100%; width: 100%的,就需要改变获取相应元素的scrollTop,同时也需要改变router.beforeEach中相应元素的scrollTop赋值
4、这种方法不仅仅限于meta存储,相应的还有 localStorage、vuex,针对于想要整个项目关闭后再次打开项目还想要关闭前的滑动距离,就需要用 localStorage 来存储,vuex和meta存储都只是暂时的,但是meta存储是最简单的,相对于其他两种不需要遍历,不需要重新获取,不需要校验路由是否相同
5、也可以参考VueKeepScrollPosition包(并不是每个项目都会生效)
安装VueKeepScrollPosition:
npm i vue-keep-scroll-position
引入VueKeepScrollPosition:
main.js写入:import VueKeepScrollPosition from 'vue-keep-scroll-position' Vue.use(VueKeepScrollPosition)
使用VueKeepScrollPosition:
<router-view v-keep-scroll-position></router-view>
原理:通过路由变化监听页面滑动距离并进行存储,在页面再次访问后获取存储的滑动距离,并改变页面的scrollTop