Skip to content
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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add useHistoryState() #2106

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 10 additions & 3 deletions packages/router/e2e/modal/index.ts
Expand Up @@ -5,11 +5,14 @@ import {
createWebHistory,
useRoute,
loadRouteLocation,
useHistoryState,
} from 'vue-router'
import {
createApp,
readonly,
ref,
watch,
shallowRef,
watchEffect,
computed,
defineComponent,
Expand Down Expand Up @@ -72,6 +75,7 @@ const Home = defineComponent({
const route = useRoute()

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

watchEffect(
() => {
Expand Down Expand Up @@ -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
}
})

Expand Down
22 changes: 22 additions & 0 deletions 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<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
@@ -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'
Expand Down