From ecc4c8e0c5ab1e349faa97c9364b1708c401f3f0 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 29 Jan 2024 13:56:23 +0000 Subject: [PATCH] fix(nuxt): prevent initial scroll jump when loading page (#25483) --- .../nuxt/src/pages/runtime/plugins/router.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/nuxt/src/pages/runtime/plugins/router.ts b/packages/nuxt/src/pages/runtime/plugins/router.ts index c02954f557..0de9129194 100644 --- a/packages/nuxt/src/pages/runtime/plugins/router.ts +++ b/packages/nuxt/src/pages/runtime/plugins/router.ts @@ -78,13 +78,25 @@ const plugin: Plugin<{ router: Router }> = defineNuxtPlugin({ startPosition = savedPosition return } - // reset scroll behavior to initial value - router.options.scrollBehavior = routerOptions.scrollBehavior - return routerOptions.scrollBehavior?.(to, START_LOCATION, startPosition || savedPosition) + if (routerOptions.scrollBehavior) { + // reset scroll behavior to initial value + router.options.scrollBehavior = routerOptions.scrollBehavior + if ('scrollRestoration' in window.history) { + const unsub = router.beforeEach(() => { + unsub() + window.history.scrollRestoration = 'manual' + }) + } + return routerOptions.scrollBehavior(to, START_LOCATION, startPosition || savedPosition) + } }, history, routes }) + + if (import.meta.client && 'scrollRestoration' in window.history) { + window.history.scrollRestoration = 'auto' + } nuxtApp.vueApp.use(router) const previousRoute = shallowRef(router.currentRoute.value)