From 0106e09e32e1bac0eeb3232e2f0f6cd44fcf3521 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Wed, 19 Oct 2022 16:33:01 +0200 Subject: [PATCH] fix(nuxt): scroll to top on dynamic routes with different params (#8327) Co-authored-by: Pooya Parsa --- .../nuxt/src/pages/runtime/router.options.ts | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/nuxt/src/pages/runtime/router.options.ts b/packages/nuxt/src/pages/runtime/router.options.ts index 1137b346dd..a654181072 100644 --- a/packages/nuxt/src/pages/runtime/router.options.ts +++ b/packages/nuxt/src/pages/runtime/router.options.ts @@ -1,5 +1,6 @@ import type { RouterConfig } from '@nuxt/schema' -import type { RouterScrollBehavior } from 'vue-router' +import type { RouterScrollBehavior, RouteLocationNormalized } from 'vue-router' +import { isEqual } from 'ohash' import { nextTick } from 'vue' import { useNuxtApp } from '#app' @@ -16,11 +17,7 @@ export default { let position: ScrollPosition = savedPosition || undefined // Scroll to top if route is changed by default - if ( - !position && - (from && to && from.matched[0] !== to.matched[0]) && - to.meta.scrollToTop !== false - ) { + if (!position && from && to && to.meta.scrollToTop !== false && _isDifferentRoute(from, to)) { position = { left: 0, top: 0 } } @@ -56,3 +53,14 @@ function _getHashElementScrollMarginTop (selector: string): number { } return 0 } + +function _isDifferentRoute (a: RouteLocationNormalized, b: RouteLocationNormalized): boolean { + const samePageComponent = a.matched[0] === b.matched[0] + if (!samePageComponent) { + return true + } + if (samePageComponent && !isEqual(a.params, b.params)) { + return true + } + return false +}