40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import { defineNuxtPlugin } from '#app'
|
|
import { useRouter } from 'vue-router'
|
|
|
|
/**
|
|
* 在路由跳转前保存当前页面的滚动位置,配合 router.options.ts 的恢复逻辑。
|
|
* 解决滚动被后续页面覆盖为 0 的问题。
|
|
*/
|
|
export default defineNuxtPlugin(() => {
|
|
if (process.server) return
|
|
|
|
const router = useRouter()
|
|
const saveScroll = (path?: string) => {
|
|
if (!path) return
|
|
try {
|
|
const pos = { left: window.scrollX, top: window.scrollY }
|
|
sessionStorage.setItem(`scroll:${path}`, JSON.stringify(pos))
|
|
} catch (err) {
|
|
console.warn('[scroll-plugin] save failed', err)
|
|
}
|
|
}
|
|
|
|
// 路由切换前先保存当前页的滚动
|
|
router.beforeEach((to, from, next) => {
|
|
saveScroll(from.fullPath)
|
|
next()
|
|
})
|
|
|
|
// 页面刷新/关闭前也保存一次当前路由的滚动
|
|
const handleBeforeUnload = () => {
|
|
const path = router.currentRoute.value.fullPath
|
|
saveScroll(path)
|
|
}
|
|
window.addEventListener('beforeunload', handleBeforeUnload)
|
|
|
|
// 清理监听
|
|
return () => {
|
|
window.removeEventListener('beforeunload', handleBeforeUnload)
|
|
}
|
|
})
|