MCPcopy
hub / github.com/nuxt/nuxt / scrollBehavior

Function scrollBehavior

packages/nuxt/src/pages/runtime/router.options.ts:13–51  ·  view source on GitHub ↗
(to, from, savedPosition)

Source from the content-addressed store, hash-verified

11// https://router.vuejs.org/api/interfaces/routeroptions
12export default <RouterConfig>{
13 scrollBehavior (to, from, savedPosition) {
14 const nuxtApp = useNuxtApp()
15 // @ts-expect-error untyped, nuxt-injected option
16 const hashScrollBehaviour = useRouter().options?.scrollBehaviorType ?? 'auto'
17
18 // Hash routes on the same page, no page hook is fired so resolve here
19 if (to.path.replace(/\/$/, '') === from.path.replace(/\/$/, '')) {
20 if (from.hash && !to.hash) {
21 return { left: 0, top: 0 }
22 }
23 if (to.hash) {
24 return { el: to.hash, top: _getHashElementScrollMarginTop(to.hash), behavior: hashScrollBehaviour }
25 }
26 // The route isn't changing so keep current scroll position
27 return false
28 }
29
30 const routeAllowsScrollToTop = typeof to.meta.scrollToTop === 'function' ? to.meta.scrollToTop(to, from) : to.meta.scrollToTop
31
32 if (routeAllowsScrollToTop === false) { return false }
33
34 if (from === START_LOCATION) {
35 return _calculatePosition(to, from, savedPosition, hashScrollBehaviour)
36 }
37
38 return new Promise((resolve) => {
39 const doScroll = () => {
40 requestAnimationFrame(() => resolve(_calculatePosition(to, from, savedPosition, hashScrollBehaviour)))
41 }
42 nuxtApp.hooks.hookOnce('page:loading:end', () => {
43 const transitionPromise = nuxtApp['~transitionPromise'] as Promise<void> | undefined
44 if (transitionPromise) {
45 transitionPromise.then(doScroll)
46 } else {
47 doScroll()
48 }
49 })
50 })
51 },
52}
53
54function _getHashElementScrollMarginTop (selector: string): number {

Callers

nothing calls this directly

Calls 5

useNuxtAppFunction · 0.90
useRouterFunction · 0.90
_calculatePositionFunction · 0.85
doScrollFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…