diff --git a/packages/router/e2e/modal/index.ts b/packages/router/e2e/modal/index.ts index 8cd329e96..0ee7570a4 100644 --- a/packages/router/e2e/modal/index.ts +++ b/packages/router/e2e/modal/index.ts @@ -5,11 +5,14 @@ import { createWebHistory, useRoute, loadRouteLocation, + useHistoryState, } from 'vue-router' import { createApp, readonly, ref, + watch, + shallowRef, watchEffect, computed, defineComponent, @@ -72,6 +75,7 @@ const Home = defineComponent({ const route = useRoute() const userId = computed(() => route.params.id) + const historyState = useHistoryState<{ backgroundView?: string }>() watchEffect( () => { @@ -187,14 +191,17 @@ router.beforeEach(to => { const app = createApp({ setup() { const route = useRoute() + const historyState = useHistoryState<{ backgroundView?: string }>() - const routeWithModal = computed(() => { + const routeWithModal = shallowRef(route) + watch(historyState, async () => { if (historyState.value.backgroundView) { - return router.resolve( + routeWithModal.value = router.resolve( historyState.value.backgroundView ) as RouteLocationNormalizedLoaded + await loadRouteLocation(routeWithModal.value) } else { - return route + routeWithModal.value = route } }) diff --git a/packages/router/src/history/state.ts b/packages/router/src/history/state.ts new file mode 100644 index 000000000..d4b66c0fa --- /dev/null +++ b/packages/router/src/history/state.ts @@ -0,0 +1,22 @@ +import { isBrowser } from '../utils' +import { useRouter } from '../useApi' +import { computed } from 'vue' +import { HistoryState } from './common' + +/** + * Reactive history state. Only available in browser. + * + * @experimental - DO NOT use in production + */ +export function useHistoryState() { + const router = useRouter() + return computed>(() => { + if (!isBrowser) { + return {} + } + + // Enforce automatically update when navigation happens + router.currentRoute.value + return window.history.state + }) +} diff --git a/packages/router/src/index.ts b/packages/router/src/index.ts index 816dd2c51..74327c3ca 100644 --- a/packages/router/src/index.ts +++ b/packages/router/src/index.ts @@ -1,4 +1,5 @@ export { createWebHistory } from './history/html5' +export { useHistoryState } from './history/state' export { createMemoryHistory } from './history/memory' export { createWebHashHistory } from './history/hash' export { createRouterMatcher } from './matcher'