From 2b3eefc3a14e69953fd50428068f0e81eb533eb2 Mon Sep 17 00:00:00 2001 From: "Xin Du (Clark)" Date: Tue, 12 Jan 2021 09:47:29 +0000 Subject: [PATCH] refactor(vue-app): simplify scrollToTop checking (#8621) --- .../vue-app/template/router.scrollBehavior.js | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/packages/vue-app/template/router.scrollBehavior.js b/packages/vue-app/template/router.scrollBehavior.js index 6acb105701..2650db696b 100644 --- a/packages/vue-app/template/router.scrollBehavior.js +++ b/packages/vue-app/template/router.scrollBehavior.js @@ -22,36 +22,34 @@ if (process.client) { } } +function shouldScrollToTop(route) { + const Pages = getMatchedComponents(route) + if (Pages.length === 1) { + const { options = {} } = Pages[0] + return options.scrollToTop !== false + } + return Pages.some(({ options }) => options && options.scrollToTop) +} + export default function (to, from, savedPosition) { // If the returned position is falsy or an empty object, will retain current scroll position let position = false - - const Pages = getMatchedComponents(to) - - // Scroll to the top of the page if... - if ( - // One of the children set `scrollToTop` - (Pages.some(Page => Page.options && Page.options.scrollToTop) || - // scrollToTop set in only page without children - (Pages.length < 2 && Pages.every(Page => !Page.options || Page.options.scrollToTop !== false))) && - // route changes - to !== from - ) { - position = { x: 0, y: 0 } - } + const isRouteChanged = to !== from // savedPosition is only available for popstate navigations (back button) if (savedPosition) { position = savedPosition + } else if (isRouteChanged && shouldScrollToTop(to)) { + position = { x: 0, y: 0 } } const nuxt = window.<%= globals.nuxt %> if ( - // Route hash changes - (to.path === from.path && to.hash !== from.hash) || // Initial load (vuejs/vue-router#3199) - to === from + !isRouteChanged || + // Route hash changes + (to.path === from.path && to.hash !== from.hash) ) { nuxt.$nextTick(() => nuxt.$emit('triggerScroll')) }