refactor(vue-app): simplify scrollToTop checking (#8621)

This commit is contained in:
Xin Du (Clark) 2021-01-12 09:47:29 +00:00 committed by GitHub
parent 3265e94979
commit 2b3eefc3a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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'))
}