修改记录位置的方式

This commit is contained in:
叮叮当
2023-09-19 10:34:49 +08:00
parent 6b41f3bb64
commit 2a41e8a726
2 changed files with 5 additions and 18 deletions

View File

@@ -30,9 +30,6 @@ app.use(vuetify)
})
.use(VuetifyUseDialog).mount('#app')
// 记录和恢复滚动位置
const scrollPositions: { [key: string]: number } = {} // 用于存储每个路由的滚动位置
// 路由导航守卫
router.beforeEach((to, from, next) => {
const isAuthenticated = store.state.auth.token !== null
@@ -41,24 +38,11 @@ router.beforeEach((to, from, next) => {
next('/login')
}
else {
// 只有 meta 中 keepAlive 为 true 的情况下才记录滚动位置
if (from.meta.keepAlive)
scrollPositions[from.fullPath] = window.scrollY
startNProgress()
next()
}
})
router.afterEach((to) => {
// 只有 meta 中 keepAlive 为 true 的情况下才恢复滚动位置
if (to.meta.keepAlive) {
const savedPosition = scrollPositions[to.fullPath]
if (savedPosition !== undefined) {
setTimeout(() => {
window.scrollTo(0, savedPosition)
}, 0)
}
}
doneNProgress()
})

View File

@@ -2,8 +2,11 @@ import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
scrollBehavior() {
// 始终滚动到顶部
scrollBehavior(to, from, savedPosition) {
// 如果页面有缓存那么恢复其位置, 否则始终滚动到顶部
if (to.meta.keepAlive && savedPosition)
return savedPosition
console.log('top: 0')
return { top: 0 }
},
routes: [