feat(router): add `replace` option to useRouter for history management (#4788)

pull/4805/head
tzyoo 3 months ago committed by GitHub
parent 875aa8b798
commit 23541b4f83
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -28,6 +28,8 @@ export interface Router {
initialLoad?: boolean
// Whether to smoothly scroll to the target position.
smoothScroll?: boolean
// Whether to replace the current history entry.
replace?: boolean
}
) => Promise<void>
/**
@ -322,7 +324,7 @@ function normalizeHref(href: string): string {
async function changeRoute(
href: string,
{ smoothScroll = false, initialLoad = false } = {}
{ smoothScroll = false, initialLoad = false, replace = false } = {}
): Promise<boolean> {
const loc = normalizeHref(location.href)
const nextUrl = new URL(href, location.origin)
@ -334,9 +336,13 @@ async function changeRoute(
return false
}
} else {
// save scroll position before changing URL
history.replaceState({ scrollPosition: window.scrollY }, '')
history.pushState({}, '', href)
if (replace) {
history.replaceState({}, '', href)
} else {
// save scroll position before changing URL
history.replaceState({ scrollPosition: window.scrollY }, '')
history.pushState({}, '', href)
}
if (nextUrl.pathname === currentUrl.pathname) {
// scroll between hash anchors on the same page, avoid duplicate entries

Loading…
Cancel
Save