]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
feat: add useHistoryState() feat/useHistoryState 2106/head
authorEduardo San Martin Morote <posva13@gmail.com>
Wed, 10 Jan 2024 10:16:49 +0000 (11:16 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Wed, 10 Jan 2024 10:16:49 +0000 (11:16 +0100)
packages/router/e2e/modal/index.ts
packages/router/src/history/state.ts [new file with mode: 0644]
packages/router/src/index.ts

index 8cd329e96ed2501334028e884e9e1f85afdd9804..0ee7570a481a6ba410793f75c67e02f2b856f623 100644 (file)
@@ -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
       }
     })
 
diff --git a/packages/router/src/history/state.ts b/packages/router/src/history/state.ts
new file mode 100644 (file)
index 0000000..d4b66c0
--- /dev/null
@@ -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
+  })
+}
index 816dd2c516c1c12a5e73ec775072c9e08c26d10b..74327c3cafeb98671f3bcf6f1bb7c8193f93e841 100644 (file)
@@ -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'