Skip to content
/ router Public

feat: add useHistoryState() #2106

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions packages/router/e2e/modal/index.ts
Original file line number Diff line number Diff line change
@@ -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<RouteLocationNormalizedLoaded>(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
}
})

22 changes: 22 additions & 0 deletions packages/router/src/history/state.ts
Original file line number Diff line number Diff line change
@@ -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<T = HistoryState>() {
const router = useRouter()
return computed<Readonly<T>>(() => {
if (!isBrowser) {
return {}
}

// Enforce automatically update when navigation happens
router.currentRoute.value
return window.history.state
})
}
1 change: 1 addition & 0 deletions packages/router/src/index.ts
Original file line number Diff line number Diff line change
@@ -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'