Skip to content

Commit 421ac36

Browse files
author
fanwei
committed
fix: make useRoute() reactive
1 parent d367145 commit 421ac36

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

src/vue-router.ts

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import Vue from 'vue'
2-
import { getCurrentInstance } from '@vue/composition-api'
2+
import { computed, ComputedRef, getCurrentInstance, reactive, shallowRef } from '@vue/composition-api'
33
import VueRouter, { NavigationGuard, Route, RouterOptions, RouteConfig } from 'vue-router'
44
import { OUT_OF_SCOPE, warn } from './utils'
55

@@ -34,36 +34,41 @@ export function createRouter(options: RouterOptions) {
3434
}
3535

3636

37-
export function useRouter() {
37+
export function useRouter(): Router {
3838
const inst = getCurrentInstance()
3939
if (inst) {
4040
return inst.proxy.$router as Router
4141
}
4242
warn(OUT_OF_SCOPE)
43-
return undefined as unknown as Router
43+
return undefined as any
4444
}
4545

46+
4647
export interface RouteLocationNormalized extends Route {}
4748
export interface RouteLocationNormalizedLoaded extends Route {}
4849

49-
const ROUTE_KEYS = [
50+
51+
const currentRoute = shallowRef(VueRouter.START_LOCATION);
52+
const computedRoute = {} as {
53+
[key in keyof Route]: ComputedRef<Route[key]>
54+
}
55+
for (const key of [
5056
'name', 'meta', 'path', 'hash', 'query',
5157
'params', 'fullPath', 'matched', 'redirectedFrom'
52-
] as const
58+
] as const) {
59+
computedRoute[key] = computed<any>(() => currentRoute.value[key]);
60+
}
61+
let reactiveRoute: Route
5362

54-
export function useRoute() {
63+
export function useRoute(): RouteLocationNormalizedLoaded {
5564
const router = useRouter()
56-
if (router) {
57-
const route = {} as RouteLocationNormalizedLoaded
58-
for (const key of ROUTE_KEYS) {
59-
Object.defineProperty(route, key, {
60-
enumerable: true,
61-
get: () => router.currentRoute[key],
62-
})
63-
}
64-
return route
65+
if (!router) return undefined as any
66+
if (!reactiveRoute) {
67+
currentRoute.value = router.currentRoute
68+
router.afterEach(to => currentRoute.value = to);
69+
reactiveRoute = reactive(computedRoute)
6570
}
66-
return undefined as unknown as RouteLocationNormalizedLoaded
71+
return reactiveRoute
6772
}
6873

6974

0 commit comments

Comments
 (0)