1.给路由对象上增加额外信息
meta: { isRecord: true, top: 0 } // isRecord是否需要设置滚动位置
2.设置组件内守卫
// 路由离开 - 触发(保存滚动位置)
beforeRouteLeave (to, from, next) {
from.meta.top = window.scrollY
next()
}
3.在全局后置钩子设置页面滚动条
// 全局后置钩子
router.afterEach((to, from) => {
// 如果当前的路由的元信息中,isRecord 的值为 true
if (to.meta.isRecord) {
setTimeout(() => {
// 则把元信息中的 top 值设为滚动条纵向滚动的位置
window.scrollTo(0, to.meta.top)
}, 0)
}
})
关于Tabs切换,保存当前位置
1.明确数据结构,在Home/index.vue中定义变量,设为对象格式{组件名:30}
const nameToTop = {}
2.tabs标签绑定before-change事件和方法实现
<van-tabs v-model="channelId" animated sticky offset-top="1.226667rem" :before-change="tabBeforeChangeFn">
<script>
methods: {
// 频道切换之前触发
tabsBeforeChangeFn () {
nameToTop[this.channelId] = window.scrollY // 先保存要被切走频道的滚动距离(一定要用哦this.channelId里存着的)
// 只有return true才会让tabs切换
return true
}
}
</script>
3.监测tabs切换后, 从nameToTop对象里拿到原本滚动位置设置
<van-tabs v-model="channelId" animated sticky offset-top="1.226667rem" :before-change="tabsBeforeChangeFn" @change="tabsChangeFn">
<script>
methods: {
// 频道切换后
tabsChangeFn (channelId) {
// 等 DOM 更新完毕之后,根据记录的"滚动条位置",调用 window.scrollTo() 方法进行滚动
this.$nextTick(() => {
window.scrollTo(0, nameToTop[channelId] || 0)
})
}
}
</script>