1
- import { usePageData } from '@vuepress/client'
2
1
import { debounce } from 'ts-debounce'
3
- import { onBeforeUnmount , onMounted , watch } from 'vue'
2
+ import { onBeforeUnmount , onMounted } from 'vue'
4
3
import { useRouter } from 'vue-router'
5
4
import type { Router } from 'vue-router'
6
5
@@ -18,7 +17,6 @@ export const useActiveHeaderLinks = ({
18
17
offset = 5 ,
19
18
} : UseActiveHeaderLinksOptions ) : void => {
20
19
const router = useRouter ( )
21
- const page = usePageData ( )
22
20
23
21
const setActiveRouteHash = ( ) : void => {
24
22
// get current scrollTop
@@ -29,12 +27,10 @@ export const useActiveHeaderLinks = ({
29
27
)
30
28
// check if we are at page top
31
29
const isAtPageTop = Math . abs ( scrollTop - 0 ) < offset
30
+
31
+ // replace current route hash with empty string when scrolling back to the top
32
32
if ( isAtPageTop ) {
33
- // replace current route hash with empty string
34
- replaceWithoutScrollBehavior ( router , {
35
- hash : '' ,
36
- force : true ,
37
- } )
33
+ updateHash ( router , '' )
38
34
return
39
35
}
40
36
@@ -101,38 +97,34 @@ export const useActiveHeaderLinks = ({
101
97
}
102
98
103
99
// replace current route hash with the active anchor hash
104
- replaceWithoutScrollBehavior ( router , {
105
- hash : anchorHash ,
106
- force : true ,
107
- } )
100
+ updateHash ( router , anchorHash )
108
101
return
109
102
}
110
103
}
111
104
112
105
const onScroll : ( ) => Promise < void > = debounce ( setActiveRouteHash , delay )
113
106
114
107
onMounted ( ( ) => {
115
- onScroll ( )
116
108
window . addEventListener ( 'scroll' , onScroll )
117
109
} )
118
110
onBeforeUnmount ( ( ) => {
119
111
window . removeEventListener ( 'scroll' , onScroll )
120
112
} )
121
- watch ( ( ) => page . value . path , onScroll )
122
113
}
123
114
124
115
/**
125
- * Call `router.replace()` and do not trigger `scrollBehavior`
116
+ * Update current hash and do not trigger `scrollBehavior`
126
117
*/
127
- export const replaceWithoutScrollBehavior = async (
128
- router : Router ,
129
- ...args : Parameters < Router [ 'replace' ] >
130
- ) : Promise < void > => {
118
+ const updateHash = async ( router : Router , hash : string ) : Promise < void > => {
131
119
// temporarily disable `scrollBehavior`
132
120
// restore it after navigation
133
121
const { scrollBehavior } = router . options
134
122
router . options . scrollBehavior = undefined
135
123
await router
136
- . replace ( ...args )
124
+ . replace ( {
125
+ query : router . currentRoute . value . query ,
126
+ hash,
127
+ force : true ,
128
+ } )
137
129
. finally ( ( ) => ( router . options . scrollBehavior = scrollBehavior ) )
138
130
}
0 commit comments