feat(nuxt): smooth scroll behavior option (#21948)

This commit is contained in:
Lucas Vargas 2023-07-19 12:30:40 -03:00 committed by GitHub
parent 22cccb0ab1
commit 5d2107bb76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 5 additions and 3 deletions

View File

@ -12,6 +12,7 @@ type ScrollPosition = Awaited<ReturnType<RouterScrollBehavior>>
export default <RouterConfig> {
scrollBehavior (to, from, savedPosition) {
const nuxtApp = useNuxtApp()
const behavior = this.scrollBehaviorType ?? 'auto'
// By default when the returned position is falsy or an empty object, vue-router will retain the current scroll position
// savedPosition is only available for popstate navigations (back button)
@ -28,7 +29,7 @@ export default <RouterConfig> {
return { left: 0, top: 0 }
}
if (to.hash) {
return { el: to.hash, top: _getHashElementScrollMarginTop(to.hash) }
return { el: to.hash, top: _getHashElementScrollMarginTop(to.hash), behavior }
}
}
@ -39,7 +40,7 @@ export default <RouterConfig> {
nuxtApp.hooks.hookOnce(hookToWait, async () => {
await nextTick()
if (to.hash) {
position = { el: to.hash, top: _getHashElementScrollMarginTop(to.hash) }
position = { el: to.hash, top: _getHashElementScrollMarginTop(to.hash), behavior }
}
resolve(position)
})

View File

@ -5,6 +5,7 @@ export type RouterOptions = Partial<Omit<_RouterOptions, 'history' | 'routes'>>
history?: (baseURL?: string) => RouterHistory
routes?: (_routes: _RouterOptions['routes']) => _RouterOptions['routes']
hashMode?: boolean
scrollBehaviorType?: 'smooth' | 'auto'
}
export type RouterConfig = RouterOptions
@ -12,4 +13,4 @@ export type RouterConfig = RouterOptions
/**
* Only JSON serializable router options are configurable from nuxt config
*/
export type RouterConfigSerializable = Pick<RouterConfig, 'linkActiveClass' | 'linkExactActiveClass' | 'end' | 'sensitive' | 'strict' | 'hashMode'>
export type RouterConfigSerializable = Pick<RouterConfig, 'linkActiveClass' | 'linkExactActiveClass' | 'end' | 'sensitive' | 'strict' | 'hashMode' | 'scrollBehaviorType'>