23 lines
614 B
TypeScript
23 lines
614 B
TypeScript
// app/plugins/scroll-memory.client.ts
|
|
// 记录离开页面时的滚动位置,方便返回时恢复
|
|
import { useRouter } from 'vue-router'
|
|
|
|
const keyOf = (path: string) => `scroll:${path}`
|
|
|
|
export default defineNuxtPlugin(() => {
|
|
if (process.server) return
|
|
|
|
const router = useRouter()
|
|
|
|
router.beforeEach((to, from) => {
|
|
if (!from?.fullPath) return true
|
|
try {
|
|
const pos = { left: window.scrollX, top: window.scrollY }
|
|
sessionStorage.setItem(keyOf(from.fullPath), JSON.stringify(pos))
|
|
} catch (err) {
|
|
console.warn('[scroll] pre-save failed', err)
|
|
}
|
|
return true
|
|
})
|
|
})
|