Skip to content

Commit 65487db

Browse files
committed
feat: add useHistoryState()
1 parent 3b060f6 commit 65487db

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

packages/router/e2e/modal/index.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,14 @@ import {
55
createWebHistory,
66
useRoute,
77
loadRouteLocation,
8+
useHistoryState,
89
} from 'vue-router'
910
import {
1011
createApp,
1112
readonly,
1213
ref,
14+
watch,
15+
shallowRef,
1316
watchEffect,
1417
computed,
1518
defineComponent,
@@ -72,6 +75,7 @@ const Home = defineComponent({
7275
const route = useRoute()
7376

7477
const userId = computed(() => route.params.id)
78+
const historyState = useHistoryState<{ backgroundView?: string }>()
7579

7680
watchEffect(
7781
() => {
@@ -187,14 +191,17 @@ router.beforeEach(to => {
187191
const app = createApp({
188192
setup() {
189193
const route = useRoute()
194+
const historyState = useHistoryState<{ backgroundView?: string }>()
190195

191-
const routeWithModal = computed(() => {
196+
const routeWithModal = shallowRef<RouteLocationNormalizedLoaded>(route)
197+
watch(historyState, async () => {
192198
if (historyState.value.backgroundView) {
193-
return router.resolve(
199+
routeWithModal.value = router.resolve(
194200
historyState.value.backgroundView
195201
) as RouteLocationNormalizedLoaded
202+
await loadRouteLocation(routeWithModal.value)
196203
} else {
197-
return route
204+
routeWithModal.value = route
198205
}
199206
})
200207

packages/router/src/history/state.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { isBrowser } from '../utils'
2+
import { useRouter } from '../useApi'
3+
import { computed } from 'vue'
4+
import { HistoryState } from './common'
5+
6+
/**
7+
* Reactive history state. Only available in browser.
8+
*
9+
* @experimental - DO NOT use in production
10+
*/
11+
export function useHistoryState<T = HistoryState>() {
12+
const router = useRouter()
13+
return computed<Readonly<T>>(() => {
14+
if (!isBrowser) {
15+
return {}
16+
}
17+
18+
// Enforce automatically update when navigation happens
19+
router.currentRoute.value
20+
return window.history.state
21+
})
22+
}

packages/router/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export { createWebHistory } from './history/html5'
2+
export { useHistoryState } from './history/state'
23
export { createMemoryHistory } from './history/memory'
34
export { createWebHashHistory } from './history/hash'
45
export { createRouterMatcher } from './matcher'

0 commit comments

Comments
 (0)