diff --git a/package.json b/package.json index 00ee454..b1710c2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vue2-helpers", - "version": "1.1.4", + "version": "1.1.5", "description": "A util package to use Vue 2 with Composition API easily", "author": "Ambit Tsai ", "license": "Apache-2.0", diff --git a/src/vue-router.ts b/src/vue-router.ts index c45e8d2..a882b0f 100644 --- a/src/vue-router.ts +++ b/src/vue-router.ts @@ -48,27 +48,36 @@ export interface RouteLocationNormalized extends Route {} export interface RouteLocationNormalizedLoaded extends Route {} -const currentRoute = shallowRef(VueRouter.START_LOCATION); -const computedRoute = {} as { - [key in keyof Route]: ComputedRef -} -for (const key of [ - 'name', 'meta', 'path', 'hash', 'query', - 'params', 'fullPath', 'matched', 'redirectedFrom' -] as const) { - computedRoute[key] = computed(() => currentRoute.value[key]); +function createReactiveRoute(initialRoute: Route) { + const routeRef = shallowRef(initialRoute); + const computedRoute = {} as { + [key in keyof Route]: ComputedRef + } + for (const key of [ + 'name', 'meta', 'path', 'hash', 'query', + 'params', 'fullPath', 'matched', 'redirectedFrom' + ] as const) { + computedRoute[key] = computed(() => routeRef.value[key]); + } + return [ + reactive(computedRoute), + (route: Route) => { + routeRef.value = route + }, + ] as const } -let reactiveRoute: Route + +let reactiveCurrentRoute: Route export function useRoute(): RouteLocationNormalizedLoaded { const router = useRouter() if (!router) return undefined as any - if (!reactiveRoute) { - currentRoute.value = router.currentRoute - router.afterEach(to => currentRoute.value = to); - reactiveRoute = reactive(computedRoute) + if (!reactiveCurrentRoute) { + let setCurrentRoute: (route: Route) => void + [reactiveCurrentRoute, setCurrentRoute] = createReactiveRoute(router.currentRoute) + router.afterEach(to => setCurrentRoute(to)) } - return reactiveRoute + return reactiveCurrentRoute }