Skip to content

Commit 0fdb021

Browse files
committed
fix(plugin-active-header-links): keep query when updating hash (close #991)
1 parent b6ded16 commit 0fdb021

File tree

1 file changed

+12
-20
lines changed

1 file changed

+12
-20
lines changed

ecosystem/plugin-active-header-links/src/client/composables/useActiveHeaderLinks.ts

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
import { usePageData } from '@vuepress/client'
21
import { debounce } from 'ts-debounce'
3-
import { onBeforeUnmount, onMounted, watch } from 'vue'
2+
import { onBeforeUnmount, onMounted } from 'vue'
43
import { useRouter } from 'vue-router'
54
import type { Router } from 'vue-router'
65

@@ -18,7 +17,6 @@ export const useActiveHeaderLinks = ({
1817
offset = 5,
1918
}: UseActiveHeaderLinksOptions): void => {
2019
const router = useRouter()
21-
const page = usePageData()
2220

2321
const setActiveRouteHash = (): void => {
2422
// get current scrollTop
@@ -29,12 +27,10 @@ export const useActiveHeaderLinks = ({
2927
)
3028
// check if we are at page top
3129
const isAtPageTop = Math.abs(scrollTop - 0) < offset
30+
31+
// replace current route hash with empty string when scrolling back to the top
3232
if (isAtPageTop) {
33-
// replace current route hash with empty string
34-
replaceWithoutScrollBehavior(router, {
35-
hash: '',
36-
force: true,
37-
})
33+
updateHash(router, '')
3834
return
3935
}
4036

@@ -101,38 +97,34 @@ export const useActiveHeaderLinks = ({
10197
}
10298

10399
// replace current route hash with the active anchor hash
104-
replaceWithoutScrollBehavior(router, {
105-
hash: anchorHash,
106-
force: true,
107-
})
100+
updateHash(router, anchorHash)
108101
return
109102
}
110103
}
111104

112105
const onScroll: () => Promise<void> = debounce(setActiveRouteHash, delay)
113106

114107
onMounted(() => {
115-
onScroll()
116108
window.addEventListener('scroll', onScroll)
117109
})
118110
onBeforeUnmount(() => {
119111
window.removeEventListener('scroll', onScroll)
120112
})
121-
watch(() => page.value.path, onScroll)
122113
}
123114

124115
/**
125-
* Call `router.replace()` and do not trigger `scrollBehavior`
116+
* Update current hash and do not trigger `scrollBehavior`
126117
*/
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> => {
131119
// temporarily disable `scrollBehavior`
132120
// restore it after navigation
133121
const { scrollBehavior } = router.options
134122
router.options.scrollBehavior = undefined
135123
await router
136-
.replace(...args)
124+
.replace({
125+
query: router.currentRoute.value.query,
126+
hash,
127+
force: true,
128+
})
137129
.finally(() => (router.options.scrollBehavior = scrollBehavior))
138130
}

0 commit comments

Comments
 (0)