route.js 文件
// 路由开关 keepAlive 控制是否开起缓存
{
path: '/search', name: 'home-search', component: () => import("@/views/v4/Search.vue"), meta: { title: "搜索", keepAlive: true },
},
// 滚动高度保存
router.beforeEach((to, from, next) => {
// 离开前记录滚动位置
if(from.meta?.keepAlive) {
sessionStorage.setItem(from.name, document.documentElement.scrollTop)
}
// 返回时恢复位置
if(to.meta?.keepAlive) {
document.documentElement.scrollTop = sessionStorage.getItem(to.name) || 0
}
next()
})