页面情况介绍:
pageA:入口页面
pageB:资讯列表页
pageC:文章详情页
需求描述
需求描述:B页面中点击资讯列表需要跳转到详情页C,此时,需要记录B页面的位置,实现C页面返回B时要定位到B页面滚动的位置。
思路
思路:B页面添加滚动事件,并存储页面滚动距离到localStorage(值:yzScollTop),当C进入B时,取出滚动值,利用scrollTop(或者scrollTo方法)将B滚动到指定位置。
滚动相关代码
mounted () {
window.addEventListener('scroll', this.handleScroll, true) // 监听(绑定)滚轮滚动事件
},
methods: {
handleScroll (e) {
// this.scrollTag = this.isMajor ? 'major-wrapper' : 'academy-wrapper'
this.scrollTag = 'news-wrapper'
if (e.target._prevClass == this.scrollTag) {
const dom = document.getElementsByClassName(this.scrollTag)
localStorage.setItem('yzScollTop', dom[0].scrollTop)
}
}
}
因为B页面数据起始加载时limit10,cursor:1,所以给pageB添加页面缓存,缓存已经加载出来的数据,便于滚动定位。
meta: { title: '院校信息', keepAlive: true }
缓存页面再次加载会触发钩子函数activated,因此在activated 中获取滚动距离,并将页面滚动到固定位置
if (localStorage.getItem('yzScollTop')) {
const dom = document.getElementsByClassName(this.scrollTag)
this.$nextTick(() => {
dom[0].scrollTop = localStorage.getItem('yzScollTop')
})
}
遇到问题:
B页面返回到A时,由于B页面有缓存,当B->A,再由A->B时,B页面的滚动跳不在顶部,因此这跟踪情况下需要B页面不缓存。
解决方案:利用路由守卫,动态设置路由的缓存树型meta
// 进入文章详情需要缓存来实现滚动到跳转前的位置,其他页面无需缓存
beforeRouteLeave (to, from, next) {
if (to.name == 'Information') {
console.log('Information')
from.meta.keepAlive = true
} else {
from.meta.keepAlive = false
}
next()
},