From 4b954cc9d5ab00c1996c0b649d3e1a9d031d3a5c Mon Sep 17 00:00:00 2001 From: jxxghp Date: Fri, 4 Aug 2023 23:18:13 +0800 Subject: [PATCH] =?UTF-8?q?keepAlive=E6=97=B6=E6=81=A2=E5=A4=8D=E6=BB=9A?= =?UTF-8?q?=E5=8A=A8=E6=9D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/main.ts b/src/main.ts index a1ceb2d4..03358e6d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -30,21 +30,35 @@ app.use(vuetify) }) .use(VuetifyUseDialog).mount('#app') -// 导航守卫 +// 记录和恢复滚动位置 +const scrollPositions: { [key: string]: number } = {} // 用于存储每个路由的滚动位置 + +// 路由导航守卫 router.beforeEach((to, from, next) => { - // 通过 Vuex Store 检查用户是否已登录 const isAuthenticated = store.state.auth.token !== null + if (to.meta.requiresAuth && !isAuthenticated) { - // 如果路由需要登录权限且用户未登录,则跳转到登录页面 next('/login') } else { - // 否则,允许继续进行路由导航 + // 只有 meta 中 keepAlive 为 true 的情况下才记录滚动位置 + if (from.meta.keepAlive) + scrollPositions[from.fullPath] = window.scrollY + startNProgress() next() } }) -router.afterEach(() => { +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() })