Skip to content

Commit 3335a6a

Browse files
committed
docs: put back router.options.ts
1 parent 15f9db9 commit 3335a6a

File tree

1 file changed

+37
-27
lines changed

1 file changed

+37
-27
lines changed

docs/app/router.options.ts

Lines changed: 37 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,48 @@
11
import type { RouterConfig } from '@nuxt/schema'
2-
// https://router.vuejs.org/api/interfaces/routeroptions.html
3-
export default <RouterConfig> {
4-
scrollBehavior (to, _form, savedPosition) {
5-
if (history.state.stop) { return }
62

7-
if (history.state.smooth) {
8-
return {
9-
el: history.state.smooth,
10-
behavior: 'smooth'
11-
}
12-
}
13-
14-
if (to.hash) {
15-
const el = document.querySelector(to.hash) as any
3+
function findHashPosition (hash): { el: any, behavior: ScrollBehavior, top: number } {
4+
const el = document.querySelector(hash)
5+
// vue-router does not incorporate scroll-margin-top on its own.
6+
if (el) {
7+
const top = parseFloat(getComputedStyle(el).scrollMarginTop)
168

17-
if (!el) { return }
18-
19-
const { marginTop } = getComputedStyle(el)
9+
return {
10+
el: hash,
11+
behavior: 'smooth',
12+
top
13+
}
14+
}
15+
}
2016

21-
const marginTopValue = parseInt(marginTop)
17+
// https://router.vuejs.org/api/#routeroptions
18+
export default <RouterConfig>{
19+
scrollBehavior (to, from, savedPosition) {
20+
const nuxtApp = useNuxtApp()
2221

23-
const offset = (document.querySelector(to.hash) as any).offsetTop - marginTopValue
22+
// If history back
23+
if (savedPosition) {
24+
// Handle Suspense resolution
25+
return new Promise((resolve) => {
26+
nuxtApp.hooks.hookOnce('page:finish', () => {
27+
setTimeout(() => resolve(savedPosition), 50)
28+
})
29+
})
30+
}
2431

25-
return {
26-
top: offset,
27-
behavior: 'smooth'
28-
}
32+
// Scroll to heading on click
33+
if (to.hash) {
34+
return new Promise((resolve) => {
35+
if (to.path === from.path) {
36+
setTimeout(() => resolve(findHashPosition(to.hash)), 50)
37+
} else {
38+
nuxtApp.hooks.hookOnce('page:finish', () => {
39+
setTimeout(() => resolve(findHashPosition(to.hash)), 50)
40+
})
41+
}
42+
})
2943
}
3044

3145
// Scroll to top of window
32-
if (savedPosition) {
33-
return savedPosition
34-
} else {
35-
return { top: 0 }
36-
}
46+
return { top: 0 }
3747
}
3848
}

0 commit comments

Comments
 (0)